Raspberry Pi_Eng_23.5.4 Running Python Program


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)
최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


23.5.4  Running Python Program

 

23.5.4.1    Creating Python Program file in IDLE

 

If you want to create a Python program file in IDLE, use menu File àNew File. This will open a blank window, which is not an Python prompt, just an empty file. Here, you can write Python code, save it as a file, and run it. Then, the processing result appears in another window. Let's enter the following sentence into a new window, save it as a file by using menu File à Save or [Ctrl + S], and then run it by using menu Run à Run Module or [F5] key. You can see that the result is displayed in the original Python Shell window.

 

n = 0
for i in range(1, 101):
    n += i
 
print("The sum of the numbers 1 to 100 is:")
print(n)

 

 

23.5.4.2    Running Python program File in Shell

 

The standard text editors [Vim], [Nano], and [Leafpad] can be used to write Python program file, and That program file can be run as a Python script in Shell. With "cd" command, move to the directory where Python program file (for example, test.py) is located, and execute "python" command. Execute the command in the format of "python test.py". The following is an example of using and executing Python program file.


 


 

23.5.4.3    Using Executable Python Program File

 

Generally speaking, a way to run a Python program file is to call Python first and have Python open and run the Python program file. However, if you have place "shebang" line on the first line of program, you can run the Python program file directly without calling Python. This is a useful way how users can directly run his own programs written by himself on Terminal screen. In this way, if you copy the Python program file to the location specified in "$PATH" environment variable of the system, you can run them by just typing the name of Python program file.

 

To do this, the Python program file first should be given an executable attribute.

 

$ chmod +x test.py

 

Try to run it by typing the program file name with path.

 

$ ./test.py

 

To execute without entering full path, copy it to the directory specified in "$PATH". In this case, we will use "/usr/local/bin/" directory.

 

$ sudo cp test.py /usr/local/bin/

 

Now it is possible to run the program file only with name and without path.

 

$ test.py

 

If you want to use it more like a basic utility, you can remove the extension. Now you can run it just by typing "test".

 

$ sudo mv /usr/local/bin/test.py /usr/local/bin/test

 

$ test