2

Let's say "D:\Temp\Subfolder\mytest.exe" is not in the PATH yet. I tried:

import os, sys, subprocess
sys.path.append("D:\Temp\Subfolder")           # 1
os.environ['PATH'] += "D:\Temp\Subfolder"      # 2

but in both cases, this fails:

os.system('mytest')
subprocess.Popen('mytest')

Question: how to set the PATH for the currently running process, such that os.system and subprocess.Popen (or those commands called by imported libraries, this is my use case) don't fail?

PS: I'm looking for a solution without having to manually edit environment variables with Windows' GUI: Control Panel > System > Advanced system settings > Environment variables > ...

Basj
  • 41,386
  • 99
  • 383
  • 673
  • I am not sure about the sys.path.append but while setting and appending 'mytest' dir to the PATH env, we need to use [os.pathsep](https://docs.python.org/3/library/os.html#os.pathsep). Any error log might help as well to conclude what's the problem here. – Jay Sep 16 '20 at 13:51
  • Could you give an example command to do that @Jay? I'm not sure how it would help here. – Basj Sep 16 '20 at 13:56
  • `os.environ['PATH'] += os.pathsep + "D:\Temp\Subfolder" `. This should let the subprocess execute `mytest`. @Basj – Jay Sep 16 '20 at 13:58
  • Oh that's right @Jay, I thought it was a *list*, in fact `os.environ['PATH']` is a string! Thanks! – Basj Sep 16 '20 at 14:39

1 Answers1

1

As mentioned by @Jay in a comment, the solution is to do:

os.environ['PATH'] += os.pathsep + r"D:\Temp\Subfolder"

(this assumes that the environment variable PATH already exists; it could be useful to check this before)

Indeed, os.environ['PATH'] is a string and not a list (this is what I initially thought).

Then, both:

os.system('mytest')
subprocess.Popen('mytest')

work.


Note: None of these work:

sys.path.append(os.pathsep + "D:\Temp\Subfolder")
sys.path.append("D:\Temp\Subfolder")
Basj
  • 41,386
  • 99
  • 383
  • 673
  • `"D:\Temp\Subfolder"` should be a raw string literal in general, e.g. `folder = r"D:\Temp\Subfolder"`. It shouldn't assume that `PATH` exists. If `'PATH' is not in os.environ` then set `os.environ['PATH'] = folder`. Else set `os.environ['PATH'] = os.environ['PATH'].rstrip(os.pathsep) + os.pathsep + folder`. To pass an updated module path (i.e. `sys.path`) to a child Python process, you can follow the exact same pattern with the `PYTHONPATH` environment variable. – Eryk Sun Sep 16 '20 at 17:42