How to start a Python program in Linux?



JasKinasis

Well-Known Member
Credits
7,597
By "start a python program" I assume you mean that you want to run a python program?

There are several ways to run python scripts and it can vary depending on:
1. The scripts permissions (whether it is executable or not)
2. Whether or not the script contains a shebang at the start - with the path to the interpreter e.g.
Code:
#!/usr/bin/env python3
If the first line in a python script appears like this, it tells the shell (e.g. bash or zsh etc) which interpreter it should use in order to run the script.
Shebang lines can be used for scripts in any interpreted scripting language.
In this case it tells the shell to run the script using the python3 interpreter.
3. Whether the script is on the systems $PATH (e.g. it is in a directory like /usr/bin, or /usr/local/bin, or $HOME/bin/ ), or if it is elsewhere
4. Whether it is written in python2 or python3

Each of these factors will affect how we'd go about running a python script.

Ideally, if the python script in question IS executable, AND it contains a shebang line which specifies the interpreter to use AND it is in a directory in $PATH. Then we can run it from anywhere in our system - in the terminal, or in any desktop launcher apps - just by using the programs name.
e.g.
Code:
nameofscript
Where nameofscript is the name of the script you want to run.


If the python script IS executable AND it contains a shebang line with the path to an interpreter AND IS NOT in a directory in $PATH, you can run it from anywhere on your system using:
Code:
/path/to/nameofscript
If the python script DOES NOT contain a shebang line, and it is NOT in $PATH - it doesn't matter if it is executable or not - you can run it like this:
Code:
python /path/to/nameofscript
Where python is the appropriate version of python to run.
so if the script is written in python2, you can use python or python2.
and if it is written in python 3 then you would use python3.
And /path/to/nameofscript is the path and filename of the python script you want to run.

Those should all work from anywhere in a terminal, or in your desktops launcher/run application.

Alternatively, for scripts that are not in the systems path, you can also open a terminal and cd into the directory containing the script and then run:
Code:
./nameofscript
NOTE: the above would ONLY work if the script contains a shebang at the start.
OR
Code:
python nameofscript
Again, where python is the appropriate version of python for the script and where nameofscript is the name of the script you want to run.
 
Last edited:
$100 Digital Ocean Credit
Get a free VM to test out Linux!


Top