How to run a Python script portably without specifying its full path How to run a Python script portably without specifying its full path windows windows

How to run a Python script portably without specifying its full path


If the directory containing run.py is on the module search path (for example, PYTHONPATH environment variable), you should be able to run it like this:

python -m run

Here is the documentation on the -m command line option:

-m module-name
Searches sys.path for the named module and runs the corresponding .py file as a script.


You can make a python script executable by adding

#!/usr/bin/env python

to the beginning of the file, and making it executable with chmod +x.


Answer after the clarification edit

I prefer the following approach to the one suggested by @F.J. because it does not require users to specify the file type. Please note that this was not specified in the original question, so his answer to the original question was correct.

Lets call the file pytest.py to avoid conflicts with a possible existing run program.

On POSIX (MacOs, linux) do what @Petr said, which is based on what @alberge said:

  • chmod +x
  • add shebang #!/usr/bin/env python
  • create a directory and add it to path. Usual locations on Linux are: ~/bin/ for a single user, /usr/local/bin/ for all users
  • symlink (cp -s) the file under your PATH with basename pytest instead of pytest.py

On windows:

  • create a dir and add it to PATH. AFAIK, there is no conventional place for that, so why not C:\bin\ and ~\bin\?
  • add .PY to the PATHEXT environment variable so that Windows will recognize files with python extension as runnable files without requiring you to type the extension
  • associate python files with the python.exe interpreter (Windows Explorer > right click > check "Always use the selected program"). There is an option on the python installer that does this for you.
  • symlink pytest with extension into the dir under PATH (using Link Shell Extension from Windows Explorer or mklink name dest from cmd )

Now system( "pytest" ); should work in both systems ( sh under Linux, cmd under Windows )