How do I find out which directories are listed in my system’s PYTHONPATH
variable, from within a Python script (or the interactive shell)?
10 Answers
You would probably also want this:
import sys
print(sys.path)
Or as a one liner from the terminal:
python -c "import sys; print('\n'.join(sys.path))"
Caveat: If you have multiple versions of Python installed you should use a corresponding command python2
or python3
.
-
Same. Linux aaa.com 2.6.18-4-686-bigmem #1 SMP Wed Jun 6 09:41:07 UTC 2007 i686 GNU/Linux ... Debian Sarge– SpechalCommented Nov 16, 2012 at 8:34
-
8This is the platform- and environment- independent way to get the current runtime's python path. Commented Nov 29, 2012 at 19:06
-
18This answer was much more helpful for my situation than the accepted answer. I know what my environment variables is. I needed to know where python decided to point besides my environment variable. Commented Apr 17, 2013 at 19:55
-
I find it easier to use the following, since it makes it clear if the empty string (
''
) is in the path:python -c "import sys, pprint; pprint.pprint(sys.path)"
( And I found this answer more helpful, too; the title of the question mislead me into thinking it was about the actual path python was using, rather than the contents of thePYTHONPATH
environment variable.)– cjsCommented Nov 1, 2017 at 4:06 -
I used
sys.path[0]
to get the "deffault" path where a local file ist stored. Oterwise I get an array with lots of paths. e.gfiel=open(MyLogfile.log, 'w')
Commented Jan 25, 2018 at 10:43
sys.path
might include items that aren't specifically in your PYTHONPATH
environment variable. To query the variable directly, use:
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
-
3(or, more generically ...split(os.sep) ). Can't figure out why you're not getting the love, Mark. Your reply is technically more accurate than Paul D Waite's own reply to his question ????– mjvCommented Sep 28, 2009 at 22:46
-
5os.sep is incorrect, see stackoverflow.com/questions/1499019/… Commented Sep 30, 2009 at 16:03
-
2And that problem with the separator is probably why I wasn't getting the love. Thanks for setting me straight. Commented Sep 30, 2009 at 16:03
-
14And if receive a KeyError, does it means that PYTHONPATH is not defined in my system? Is that a problem? Thanks– glarrainCommented Sep 13, 2011 at 19:56
-
9@glarrin, correct - KeyError means that PYTHONPATH is not defined. It won't be a problem because there's already default paths set up, see
sys.path
. Commented Sep 13, 2011 at 20:03
Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.pathsep as below:
sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:
import os
os.environ.get('PYTHONPATH', '').split(os.pathsep)
-
8For future readers:
os.sep
returns the directory separator for the operating system, e.g./
. The separator used in the Python path is different, and returned byos.pathsep
as shown in the accepted answer. Commented May 22, 2010 at 10:35 -
1Thanks for the fix. I always get them mixed up when writing code by hand.– VitaliCommented Mar 31, 2022 at 18:02
PYTHONPATH is an environment variable whose value is a list of directories. Once set, it is used by Python to search for imported modules, along with other std. and 3rd-party library directories listed in Python's "sys.path".
As any other environment variables, you can either export it in shell or in ~/.bashrc, see here. You can query os.environ['PYTHONPATH'] for its value in Python as shown below:
$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"
IF defined in shell as
$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite
THEN result =>
/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
ELSE result =>
PYTHONPATH is not defined
To set PYTHONPATH to multiple paths, see here.
Note that one can add or delete a search path via sys.path.insert(), del or remove() at run-time, but NOT through os.environ[]. Example:
>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>>
In summary, PYTHONPATH is one way of specifying the Python search path(s) for imported modules in sys.path. You can also apply list operations directly to sys.path without the aid of PYTHONPATH.
-
Being that you're using brackets and not
.get()
, if PYTHONPATH is not defined, you'll simply get a traceback error and neither the path nor "PYTHONPATH is not defined" are printed. Replace it withprint(os.environ.get('PYTHONPATH'));
and the output will default toNone
instead of failing.– Swirle13Commented Jan 9, 2023 at 19:47 -
Since
os.environ['PYTHONPATH']
is a string, in order to print one entry per line, issuefor p in os.environ['PYTHONPATH'].split(';'): print(p)
Commented Apr 25 at 2:47 -
What i'm saying is, your first code block will fail and exit and not hit
else print('PYTHONPATH is not defined')
whenPYTHONPATH
is not defined because it's not defined. Trying to access it directly via square brackets when checking will exit via Traceback instead of printing "PYTHONPATH is not defined". To make this check work properly, you need to change the code block topython3 -c "import os, sys; print(os.environ.get('PYTHONPATH')); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"
– Swirle13Commented Apr 25 at 16:55
Works in windows 10, essentially identical to vanuan's answer, but cleaner (taken from somewhere, can't remember where..):
import sys
for p in sys.path:
print(p)
-
1This one line does the same job
import sys; print('\n'.join(sys.path))
– PM0087Commented Feb 15, 2022 at 9:44
import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')
-
This is not relevant to the question;
PYTHONPATH
is not "where Python lives", but an environment variable with additional paths to search for modules. Commented Jul 7, 2022 at 7:16
Python tells me where it lives when it gives me an error message :)
>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\martin\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'PYTHONPATH'
>>>
-
This is not relevant to the question;
PYTHONPATH
is not "where Python lives", but an environment variable with additional paths to search for modules. Commented Jul 7, 2022 at 7:14
import sys
for a in sys.path:
a = a.replace('\\\\','\\')
print(a)
It will give all the paths ready for place in the Windows.
-
Calling
.replace
on a string does not modify the string, but instead creates a new one which is ignored in this code. Not that it matters, because there is no good reason to unescape the backslashes anyway. Path strings fromsys.path
are usable on that system as is. Commented Jul 7, 2022 at 7:16
Use the command,
$ which python
remember to enter this in the correct environment so use:
$ conda activate <env>
or
$ mamba activate <env>
If you do not have a conda environment, $ which python
or $ which python3
would do just fine.
-
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.– Community BotCommented Mar 7, 2022 at 4:54
-
This is not relevant to the question;
PYTHONPATH
is not "where Python lives", but an environment variable with additional paths to search for modules. Commented Jul 7, 2022 at 7:14 -
1) This is not the python path. 2) Even if it was. What the hell is conda and mamba. Most python installs are NOT anaconda, particularly on machines with a "which" command.– ShayneCommented Jul 5 at 6:36
PYTHONPATH
. Usesys.path
for that.sys.path
is "A list of strings that specifies the search path for modules" - docs.python.org/2/library/sys.html#sys.path. PYTHONPATH is an environment variable that effects this list. By any reasonable definitionsys.path
is your "python path".python -m site
.