问题
I am trying to automate executable creation for my program in 32 and 64bit with cx_Freeze. I have two separate python 3.4 installations (32 and 64 bit) with all required packages, which all correspond to their appropriate architectures.
However, when I execute the script that calls the different python installations via subprocess, the called python subprocesses import the wrong packages. They both import the packages, the original script was called from and not the packages the python installation, that was called in the subprocess.
Minimal example called with a 64bit python:
#! coding=utf-8
import subprocess as sp
sp.call(["python34-32","test.py"])
sp.call(["python34","test.py"])
The test.py contains only the line:
import cx_Freeze
The second process, that also calls the 64bit python won't have a problem. But the 32bit will throw the following error:
ImportError: DLL load failed: %1 is not a valid Win32 application.
This is because the subprocess, which is calling 32bit python, imports cx_freeze from the 64bit python. The situation can also be reversed. When the main script is executed with a 32bit python, the same error occurs, however, now it is because the 64bit python called in the suprocess is importing the 32bit freeze package.
How can I stop this behavior and tell it to import from the appropriate source?
I am using Windows 7 x64 and PyDev as IDE, in case it is relevant, which it probably is.
EDIT: So apparently it works when the Main Script is executed from command line inside the source directory. Thanks to the comments below, I guess the problem has to with how PyDev sets the environment variables.
回答1:
Apparently PyDev sets the environment variable PYTHONPATH and this is the path that both subprocesses use to load their packages.
If I execute the following script in a 64 bit python:
#! coding=utf-8
import subprocess as sp
sp.call(["python34-32", "test.py"])
whereas test.py
contains the lines:
import os
print(os.getenv("PYTHONPATH"))
the result shows the standard folders as they are set for the 64bit python installation.
My guess is, I have to change the PYTHONPATH variable before calling the 32bit python. Does anyone know how to do that?
EDIT: Changing the PYTHONPATH variable in the environment of the subprocess did the trick. Executing the following in a 64bit python will work
#! coding=utf-8
import subprocess as sp
import os
env = os.environ
env["PYTHONATH"] = "{INSERT FOLDERS TO 32bit PYTHON}"
sp.call(["python34-32", "test.py"], env=env)
Thanks to bakuriu for getting me on the right track.
来源:https://stackoverflow.com/questions/25913184/importing-wrong-packages-when-calling-a-python-script-from-another-python-script