48

I have set path using

sys.path.insert(1, mypath)

Then, I tried to print contents of PYTHONPATH variable using os.environ as below

print(os.environ['PYTHONPATH'])

but I am getting error as

    raise KeyError(key)
KeyError: 'PYTHONPATH'

How can we print contents of PYTHONPATH variable.

  • Obviously that means you don't have python path set in your machine. – thavan Aug 28 '13 at 11:27
  • @thavan shouldn't sys.path.insert set the PYTHONPATH variable? –  Aug 28 '13 at 11:37
  • 1
    One thing to note: sys.path is initialized from a number of locations, one of which is the environment variable PYTHONPATH. However, updating sys.path does not update PYTHONPATH. – Simon Callan Aug 28 '13 at 11:42
  • @Drt no it shouldn't - it's set in the environment before Python runs... it's something Python can pick up and use... Most child processes can't affect the parents environment anyway... So as I mentioned in my answer - what are you actually trying to do? – Jon Clements Aug 28 '13 at 11:46
  • What is the problem you are trying to solve? – Burhan Khalid Aug 28 '13 at 11:54
  • @Drt I don't think so. Python searches modules in $PATH and well as in $PYTHONPATH. But they are different. $PATH is common for all programs. – thavan Aug 30 '13 at 11:03

2 Answers2

69

I suggest not to rely on the raw PYTHONPATH because it can vary depending on the OS.

Instead of the PYTHONPATH value in the os.environ dict, use sys.path from the sys module. This is preferrrable, because it is platform independent:

import sys
print(sys.path)

The value of sys.path is initialized from the environment variable PYTHONPATH, plus an installation-dependent default (depending on your OS). For more info see

https://docs.python.org/2/library/sys.html#sys.path

https://docs.python.org/3/library/sys.html#sys.path

mit
  • 11,083
  • 11
  • 50
  • 74
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • there must/should be some common variable for `PYTHONPATH` in all platforms. If it differs, I guess we are better of using sys.path then. –  Aug 28 '13 at 11:41
  • 1
    Why do you want to use the raw PYTHONPATH while `sys.path` is based on this variable plus some other default dir (depending on your OS) ? See http://docs.python.org/2/library/sys.html#sys.path for more info. – Maxime Lorant Aug 28 '13 at 11:42
  • I thought it is other way around, i.e. PYTHONPATH depends on sys.path. Anyway, thanks –  Aug 28 '13 at 13:11
9

If PYTHONPATH hasn't been set then that's expected, maybe default it to an empty string:

import os
print(os.environ.get('PYTHONPATH', ''))

You may also be after:

import sys
print(sys.path)
mit
  • 11,083
  • 11
  • 50
  • 74
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • I have tried defaulting to an empty string. And then did `sys.path.insert(1, mypath)`. But no change. I am still getting error for `print(os.environ['PYTHONPATH'])` as keyerror. –  Aug 28 '13 at 11:33
  • @Drt what are you actually trying to do? – Jon Clements Aug 28 '13 at 11:45