Fix Python – How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

Question

Asked By – Randy Skretka

How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not
found. When I cd to the directory holding the script the script runs. So what good is the
PYTHONPATH?

$ echo $PYTHONPATH
:/home/randy/lib/python

$ tree -L 1 '/home/randy/lib/python' 
/home/randy/lib/python
├── gbmx_html.py
├── gbmx.py
├── __init__.py
├── __pycache__
├── scripts
└── yesno.py

$ python gbmx.py -h
python: can't open file 'gbmx.py': [Errno 2] No such file or directory

$ cd '/home/randy/lib/python'

After cd to the file directory it runs ..

$ python gbmx.py -h
usage: gbmx.py [-h] [-b]

Why can I not make any use of the PYTHONPATH?

Now we will see solution for issue: How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?


Answer

I think you’re a little confused. PYTHONPATH sets the search path for importing python modules, not for executing them like you’re trying.

PYTHONPATH Augment the default search path for module files. The
format is the same as the shell’s PATH: one or more directory
pathnames separated by os.pathsep (e.g. colons on Unix or semicolons
on Windows). Non-existent directories are silently ignored.

In addition to normal directories, individual PYTHONPATH entries may
refer to zipfiles containing pure Python modules (in either source or
compiled form). Extension modules cannot be imported from zipfiles.

The default search path is installation dependent, but generally
begins with prefix/lib/pythonversion (see PYTHONHOME above). It is
always appended to PYTHONPATH.

An additional directory will be inserted in the search path in front
of PYTHONPATH as described above under Interface options. The search
path can be manipulated from within a Python program as the variable
sys.path.

http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH

What you’re looking for is PATH.

export PATH=$PATH:/home/randy/lib/python 

However, to run your python script as a program, you also need to set a shebang for Python in the first line. Something like this should work:

#!/usr/bin/env python

And give execution privileges to it:

chmod +x /home/randy/lib/python/gbmx.py

Then you should be able to simply run gmbx.py from anywhere.

This question is answered By – Pedro Werneck

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0