Python – How to Run a Python Program Directly

python

How to run a Python program directly?

I have created a .py file (say, mnik.py) in gedit. It runs smoothly in terminal.

Command goes

python3 mnik.py

But whenever I click on the file it is opened with gedit. I cannot run it directly by clicking.

What to do?

Best Answer

There's two things needed.

  1. A script must have #! line telling the OS which interpreter to use. In your case your very first line in the code must be #!/usr/bin/env python3
  2. You need to open file manager , go to Edit -> Preferences -> Behavior, and select what to do with executable files

    enter image description here

    1. Finally , make sure your file itself actually has executable permissions set. In terminal you can do chmod +x /path/to/script.py and in GUI, right click on the file and alter its Properties -> Permissions

    enter image description here

    enter image description here

Note about shebang line

The very first line is called shebang line and must start with #! ; whatever comes next is the name of the interpreter that will read your code. In case you are using python3 you could use either #!/usr/bin/python3 or #!/usr/bin/env python3 for portability. If you are not using code that will be specific to python version - just use #!/usr/bin/env python

Note on the script output:

If your script prints output to console, it will need to have terminal window, or alternatively use GUI dialogs such as zenity. Prefer using Run in Terminal option if you want to see the code. If you want the script to do something without seeing console output - use Run option.

enter image description here

In addition, if you have command line parameters , such as sys.argv[1] in the script , you can't set them unless you have terminal window open.

Related Question