2

So, when I import a certain module in my python script, a new path gets added to os.environ['PATH']. Also I launch my script in conda enviroment, which also adds a bunch of new entries to PATH. Is there an any way I can get original value of PATH (original in a sense that what I would get if I call echo $PATH or echo %PATH% in system's terminal)?

The reason I need this is because I need to call a specific binary in my script with subprocess.run. The binary I'm executing and the library I'm importing in my script are related in a sense that they are based on the same project, which causes my binary to fail when PATH contains entry to module's dll files. If I don't import this module a call to subprocess.run works fine, but if I do it fails without any error.

Of course If I know what path I need to remove from the PATH it is easy to modify os.environ['PATH']:

path_to_remove = r"C:\ProgramData\Anaconda3\envs\ppp\lib\site-packages\mip\libraries\win64"
saved_path = os.environ['PATH'] 
path_list = os.environ['PATH'].split(os.pathsep)
path_list.remove(path_to_remove)
os.environ['PATH'] = os.pathsep.join(path_list)
# a call to subprocess.run
os.environ['PATH'] = saved_path 
# Or you can copy os.environ, modify it and pass it as env argument to subprocess.run

But I'm looking for more stable, preferably cross-platform way of doing it.

0

1 Answer 1

1

You can save the original value of the environment variable in a separate variable before you import the said module, so that you can restore the value of the environment variable from that variable before calling subprocess.run. Use unittest.mock.patch.dict as a context manager around the call to make the modification to PATH temporary:

from unittest.mock import patch
import os
original_path = os.environ['PATH'] # save the original path before importing mip

...

import mip

...

with patch.dict('os.environ', {'PATH': original_path}):
    subprocess.run(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.