Dark theme

Key ideas in depth: Running python files


In theory, operating systems should be able to run Python files when a user double-clicks them, however, it much depends on how the user has their OS set up. They will, for example, have to have installed the Python Runtime.

In Windows, .py files should be associated with either python.exe (which opens a command prompt when it runs) or pythonw.exe (which doesn't). However, this frequently isn't the case (for example, after installing Anaconda, mine defaults to Spyder) and users will have to either "Open with..." Python or set this as their default.

For POSIX systems (*nix and Macs), adding this standard shebang line to very top of each file should allow the file to start automatically when control-clicked:

#! /usr/bin/python

However, again, this is complicated: for more info, see the Python docs.


At the end of the course we'll come back to installers and compiled Python. For now, the simplest way to allow users to double/control-click and run a file is to supply a shell script that does the job for them. Shell scripts are short programs that run in the operating system. You can find out more about shells on Wikipedia and shellscripts. If you want to learn a full shellscripting language we'd recommend bash (tutorial), which is a POSIX language, but which runs at the GitHub command line or natively on Windows as well.

In Windows, simple double-clickable shell scripts can be written with MS-DOS commands (list), saved as a .bat file. For POSIX systems, the file would be in bash script and saved as .sh . In both cases, the file would be in the same directory as the .py file, and just contain:

python filename.py

This will invoke the Python interpreter if it is installed and listed in the PATH environment variable (environment variables are variables the OS holds, and PATH is a list of where to look up programs to run). If Python isn't likely to be in the user's PATH, you need give them an installer that sets this up.

Note, however, that this way of starting Python will flash up a command prompt, but it will disappear as soon as the program has run. If you want the user to read output after the program has run, you'll need to tell the shell to keep the prompt open. In Windows you can do this with an additional line:

python filename.py
PAUSE

And in bash:

python filename.py
read

Have a go at seting up a shell script to run a "Hello World" program, and see what the difference is, with and without the additional commands.