Home > Article > Backend Development > How to execute python script
Python is a computer programming language. It is an object-oriented dynamic type language that was originally designed for writing automated scripts (shells). With the continuous updates of the version and the addition of new language features, it is increasingly used for the development of independent and large-scale projects.
3 ways to execute python scripts:
1. Turn on interactive mode
Execute Python in interactive mode. In this mode, there is no need to create a script file, just write the corresponding Python statement directly in the interactive mode of the Python interpreter. Under Windows:
Find "Command Prompt" in the start menu, open it, and enter the command line mode:
Enter: python in the command line mode to enter the interactive mode of Python
Linux:
Enter python directly in the terminal. If python3 is installed, enter the corresponding version of the Python interactive environment according to the name of the soft connection you created. For example, I use python3 to create the soft connection, so enter python3.
To exit interactive mode, just enter exit() directly.
2. Output through script
Write a script file through a text editor, name it hello.py, and enter python hello.py in command line mode
In this method, pay attention to the path of the script file. If the current working path and the script file are not in the same path, enter the path of the script file, or give the full path of the script file.
1) Enter the path where the script file is located and execute
C:\Windows\System32>G: G:\test>python hello.py Hello World!
2) Give the full path of the script file
C:\Windows\System32>python G:\test\hello.py Hello World!
3. Specify the python program in the script file Path, modify the file to an executable file, and then run the file directly
1) Modify the file and add #!/usr/bin/python3
[Vicky@localhost code]$ vi hello.py [Vicky@localhost code]$ cat hello.py #!/usr/bin/python3 print("Hello World!")
2) Modify the file permissions, Add executable permissions
[Vicky@localhost code]$ chmod u+x hello.py [Vicky@localhost code]$ ls -la hello.py -rwxrw-r--. 1 Vicky Vicky 41 10月 19 15:40 hello.py
3) Run
[Vicky@localhost code]$ ./hello.py Hello World!
When executing in this way, the interpreter must be specified in the script file, otherwise the script file cannot be run directly
[Vicky@localhost code]$ cat hello.py print("Hello World!") [Vicky@localhost code]$ ls -la hello.py -rwxrw-r--. 1 Vicky Vicky 22 10月 19 15:40 hello.py [Vicky@localhost code]$ ./hello.py ./hello.py:行1: 未预期的符号 `"Hello World!"' 附近有语法错误 ./hello.py:行1: `print("Hello World!")'
The above is the detailed content of How to execute python script. For more information, please follow other related articles on the PHP Chinese website!