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?
I want to change the system environment variable only for the execution of the current script