python subprocess Popen environment PATH?

I'm confused about how subprocess searches for the executable when using Popen(). It works if given absolute paths to the child process, but I'm trying to use relative paths. I've found that if I set the environment variable PYTHONPATH then I can get imported modules from that path ok, and PYTHONPATH is there in sys.path, but it doesn't seem to help with the behaviour of subprocess.Popen. I've also tried editing the sitecustomize.py file adding PYTHONPATH to os.environ, like so

# copy PYTHONPATH environment variable into PATH to allow our stuff to use
# relative paths for subprocess spawning
import os
if os.getenv('PYTHONPATH') is not None and os.getenv('PATH') is not none:
    os.environ['PATH'] = ':'.join([os.getenv('PATH'), os.getenv('PYTHONPATH')])

and verified that when starting up python , either interactively, with ipython, or by running a script from the command line, that PYTHONPATH is successfully appearing in os.environ. However, subrocess.Popen still doesn't search there for the executable. I thought it was supposed to inherit the parents environment, if no env kwarg is specified? Next I tried giving env explicitly, first by making a copy of os.getenv and secondly just by giving env={'PATH': '/explicit/path/to/search/from'}, and it still does not find the executable. Now I'm stumped.

Hopefully an example will help explain my problem more clearly:

/dir/subdir1/some_executable
/dir/subdir2/some_script.py

# some_script.py
from subprocess import Popen, PIPE
spam, eggs = Popen(['../subdir1/some_executable'], stdout=PIPE, stderr=PIPE).communicate()

Если я нахожусь в / dir / subdir2 и запускаю python some_script.py , он работает, но если я нахожусь в ] / dir и я запускаю python subdir2 / some_script.py , хотя / dir / subdir2 находится в os.environ ['PATH'] , то подпроцесс выдаст OSError: [Errno 2] Нет такого файла или каталога .

56
задан wim 21 May 2015 в 02:00
поделиться