Trying to learn how to run my scripts through Ubuntu's terminal regularly. That being said I am familiar with bash, wget, and awk being called but how do I call python files to run in the terminal? I would like to learn this but I am unsure on where to research it. I have a .pyw file that references several .py files in a folder.
7 Answers
Option 1: Call the interpreter
- For Python 2:
python <filename>.py - For Python 3:
python3 <filename>.py
Option 2: Let the script call the interpreter
- Make sure the first line of your file has
#!/usr/bin/env python. - Make it executable -
chmod +x <filename>.py. - And run it as
./<filename>.py
Just prefix the script's filename with python. E.g.:
python filename.py
- 14,504
- 240
It's also worth mentioning that by adding a -i flag after python, you can keep your session running for further coding. Like this:
python -i <file_name.py>
- 61
python <filename.py>
pyw should run in the same manner, I think. You can also start an interactive console with just
python
Also, you can avoid having to invoke python explicitly by adding a shebang at the top of the script:
#!/usr/bin/env python
... or any number of variations thereof
- 827
Change directories using cd to the directory containing the .py and run one of the following two commands:
python <filename>.py # for Python 2.x
python3 <filename>.py # for Python 3.x
Alternatively run one of the following two commands:
python /path/to/<filename>.py # for Python 2.x
python3 /path/to/<filename>.py # for Python 3.x
- 122,292
- 133
- 301
- 332
First run following command
chmod +x <filename>.py
Then at the top of the script, add #! and the path of the Python interpreter:
#!/usr/bin/python
If you would like the script to be independent of where the Python interpreter lives, you can use the env program. Almost all Unix variants support the following, assuming the Python interpreter is in a directory in the user's $PATH:
#! /usr/bin/env python
Try using the command python3 instead of python. If the script was written in Python3, and you try to run it with Python2, you could have problems. Ubuntu has both; changing the program name to python3 (instead of replacing python) made this possible. Ubuntu needs v2.7 (as of 2/16/2017) so DON'T delete or remove Python2, but keep them both. Make a habit of using Python3 to run scripts, which can run either.