Reputation: 211
I am running python 3.9 on Windows.
print(sys.path)
currDir = os.getcwd()
currDir += "\node"
sys.path.append(currDir)
print(sys.path)
I see the 2nd print out of sys.path
has my c:\working\node\
But my issue is when I run the command under c:\working\node\
, e.g. npm install
p = subprocess.Popen(["npm.cmd", "install]),
I get error saying 'The system cannot find the file specified'
And after my script is run , I try 'echo %PATH%', I don't see c:\working\node\
in the %PATH% varaible too?
Can you please tell me how can I add a new directory to system path variable so that subprocess.Popen
can see the new addition?
Upvotes: 3
Views: 5290
Reputation: 5518
Despite the name, sys.path
is NOT the system PATH. It is (from the documentation):
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.
Additionally, any changes to the environment won't propagate to a new process you open w/in a python session unless you tell it explicitly to do so.
You can solve both of these with the env
flag of Popen
You can get the current environment from os.environ
, then simply extend the PATH variable and pass this environment through to Popen
via the env flag
Something like:
new_env = os.environ.copy()
new_env['PATH'] = os.pathsep.join((new_env['PATH'].split(os.pathsep) if 'PATH' in new_env else []) + [currDir])
p = subprocess.Popen(["npm.cmd", "install"], env=new_env)
Additionally, make sure you are properly escaping your paths on Windows if using backslash, see this answer for more details
currDir += "\\node"
Upvotes: 1
Reputation: 743
sys.path
is not the same as the PATH
variable specifying where to search for binaries:
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.
You want to set the PATH
variable in os.environ
instead.
app_path = os.path.join(root_path, 'other', 'dir', 'to', 'app')
os.environ["PATH"] += os.pathsep + os.path.join(os.getcwd(), 'node')
Upvotes: 2