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.
-
Differential case in the following because the original title too general including it - about running python script in terminal to call a function stackoverflow.com/q/25837063/54964– Léo Léopold Hertz 준영Jun 25, 2017 at 9:19
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
-
what is the reason, that when I want to run my .py it works only work with your method option 1, and the second gives a syntax error?– KrsztrOct 3, 2018 at 9:11
-
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>
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
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
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
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.
-
2
-
My bad, your right. Thats probably why Ubuntu still uses python 2. Sorry wjandrea, thanks for correcting me.– TonyFeb 18, 2017 at 2:09