Add folder to PYTHONPATH programmatically

Issue

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:

test.py

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
code

D:\Project> dir *.py /b
test.py

D:\Project> python test.py
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
subprocess.run(["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?

Solution

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 = 'PYTHONPATH'

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

print('BEFORE:', pythonpath)

folder = Path(__file__).resolve().parent.joinpath('code')
print(f'{folder=}')

pathlist = [str(folder)]
if pythonpath:
    pathlist.extend(pythonpath.split(os.pathsep))
print(f'{pathlist=}')

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