Add folder to PYTHONPATH programmatically


The environment variable PYTHONPATH is set to C:\Users\Me. I’d like to add to PYTHONPATH a folder named code which is located in the same directory as my script (D:\Project). This is what I tried:

import os
from pathlib import Path

print('BEFORE:', os.environ['PYTHONPATH'])

folder = Path(__file__).resolve().parent.joinpath('code')
print('FOLDER:', folder)

os.system(f'set PYTHONPATH={folder};%PYTHONPATH%')
print('AFTER:', os.environ['PYTHONPATH'])
Sample run:
D:\Project> dir /ad /b

D:\Project> dir *.py /b

D:\Project> python
BEFORE: C:\Users\Me
FOLDER: D:\Project\code
AFTER: C:\Users\Me     <<< should be D:\Project\code;C:\Users\Me

I also tried this:

import subprocess["set", f"PYTHONPATH={folder};%PYTHONPATH%"])

And this is what I got:

FileNotFoundError: [WinError 2] The system cannot find the file specified

How can I add a folder to PYTHONPATH programmatically?


If you only want to change it for the execution of the current script, you can do it simply by assigning (or changing an existing) value in the os.environ mapping. The code below is complicated a bit by the fact that I made it work even if os.environ[PYTHONPATH] isn’t initially set to anything (as is the case on my own system).

import os
from pathlib import Path


    pythonpath = os.environ[PYTHONPATH]
except KeyError:
    pythonpath = ''

print('BEFORE:', pythonpath)

folder = Path(__file__).resolve().parent.joinpath('code')

pathlist = [str(folder)]
if pythonpath:

os.environ[PYTHONPATH] = os.pathsep.join(pathlist)
print('AFTER:', os.environ[PYTHONPATH])

Answered By – martineau

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published