Basj
Basj

Reputation: 46257

Add to PATH for later use with os.system or subprocess.Popen in the same script

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 > ...

Upvotes: 2

Views: 906

Answers (1)

Basj
Basj

Reputation: 46257

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")

Upvotes: 1

Related Questions