How to execute a python script?

I wrote a python script, some guy told me to put the following at the top/

#!/usr/bin/python

Which I did. Does this mean that the script needs to be saved to this directory? Currently the script is saved in the “Python Scripts” folder in the Desktop.

So how do I actually the execute the script? Do I just type “python scriptname.py” when im in the right directory? How to I change the directory?

No, it means the script will call the python interpreter in /usr/bin/python when it is run.

From the CLI you can execute it by:

cd scriptdirectory
chmod 755 thescript.py
./thescript.py

The chmod has only to be done once. Or you can do:

python thescript.py

and you don’t need the chmod. Naturally, substitute your directory names and script names in the above, and not blindly use my names.

If using the GUI, you can make it executable from your file browser (which effectively does the chmod) and then click on the icon to run it.

In general,if there is sufficient authority,
you can execute

Python scriptfile.py

or

./scriptfile.py

  1. The line:

#!/usr/bin/python

tells your computer where to find the Python interpreter. So, to answer your first question… no, your script should not be in that folder.

  1. Your scripts can be executed in several ways.

a) If your script is within your PATH then you can just type the name of your script. On many Unix like systems the folder /home/username/bin is added to the PATH automatically. So, any scripts that are in that folder should launch automatically whenever you type in the script name. (I’m not sure if this holds true for OpenSuse, I’ll have to check later.)

b) If it is not in your PATH then you need to start your script with either…
b1) ./scriptName.py
or
b2) python scriptName.py

You can check which directories are in your PATH by executing the command:

echo $PATH