63

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.

Casper
  • 2,998
  • 10
  • 33
  • 56
user9447
  • 1,905
  • 5
  • 27
  • 40
  • Differential case in the following because the original title too general including it - about running python script in terminal to call a function https://stackoverflow.com/q/25837063/54964 – Léo Léopold Hertz 준영 Jun 25 '17 at 09:19

7 Answers7

106

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

  1. Make sure the first line of your file has #!/usr/bin/env python.
  2. Make it executable - chmod +x <filename>.py.
  3. And run it as ./<filename>.py
abhshkdz
  • 3,989
10

Just prefix the script's filename with python. E.g.:

python filename.py
wjandrea
  • 14,236
  • 4
  • 48
  • 98
6

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>
keyanm
  • 61
4
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

2

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 
karel
  • 114,770
2

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
wjandrea
  • 14,236
  • 4
  • 48
  • 98
Shanaka
  • 141
  • 4
-2

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.

wjandrea
  • 14,236
  • 4
  • 48
  • 98
Tony
  • 1