How To Run A Python Script Portably Without Specifying Its Full Path
Solution 1:
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
Searchessys.path
for the named module and runs the corresponding.py
file as a script.
Solution 2:
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
.
Solution 3:
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 basenamepytest
instead ofpytest.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 thePATHEXT
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 underPATH
(using Link Shell Extension from Windows Explorer ormklink name dest
from cmd )
Now system( "pytest" );
should work in both systems ( sh
under Linux, cmd
under Windows )
Solution 4:
- Make python file executable (as "alberge" stated above)
- Create some directory and put this directory into your PATH variable
- In this directory, create links to your python scripts
Post a Comment for "How To Run A Python Script Portably Without Specifying Its Full Path"