Is there a better way to control PYTHONPATH for a subprocess?

I have a set of scripts that should modify os.sys.path "on the fly." Then the scripts start the subprocess. Ideally, the subprocess will have the same os.sys.path as the caller. I want to avoid passing it as an argument, as this will require a modification of the script subprocess.

I have code that works and meets all my needs. I want to know if there is a better way to do this, and if there are any pitfalls for this approach.

Main process

import os import sys import subprocess #append a dir thats not on the sys path sys.path.append('C:/pytest2/') #convert the sys.path into env variable format pypath = '' for d in sys.path: pypath = pypath + d + ';' #create a temp copy of the env variables myenv = os.environ.copy() #set PYTHONPATH to match this scripts sys.path myenv['PYTHONPATH'] = pypath #setup a python command to echo the sys.path command = 'python C:/pytest/test_subprocess.py' #launch the subprocess with the custom env p = subprocess.Popen(command, env=myenv) 

C: /pytest/test_subprocess.py

 import sys print 'sys path' print sys.path 

Starting the main process leads to the conclusion of this console

enter image description here

As you can see, C: / pytest2 / is located on os.sys.path for test_subprocess.py

EDIT Changed os.sys for sys

+4
source share
1 answer

The PYTHONPATH environment variable is simply added to sys.path . Python itself (and the site module) initializes the module search path from various sources. You only need to add your one directory through the PYTHONPATH environment variable. Even better would be to simply install it in the regular directory of package sites that has already been verified. Then you do not have to do something special in the environment.

-3
source

Source: https://habr.com/ru/post/1436255/


All Articles