Question

I have created a PyQt app using python 3.3 and Qt4.8 and I am starting a QProcess from it. The newly started child process tries to run a python script and this script fails because it searches for python modules in 3.3 directory (default python on system is 2.7).

I think it is searching for python modules in python 3.3 directory because child process inherits its environment (and therefore PYTHONPATH) from parent process. I can change PYTHONPATH using QProcess.setProcessEnvironment but how do I get the value of PYTHONPATH for 2.7 within a PyQt app which is using python 3.3?

EDIT: The answer below by Viktor worked for me. I needed to remove PYTHONPATH and PYTHONHOME from the environment. I needed to remove PYTHONHOME because otherwise launcher was being used from my app's local directory ( I created app/package using py2app ). Below is the code:

systemEnvironment = QtCore.QProcessEnvironment.systemEnvironment()
systemEnvironment.remove( 'PYTHONPATH' )
systemEnvironment.remove( 'PYTHONHOME' )
process.setProcessEnvironment( systemEnvironment )
Was it helpful?

Solution

# Get the current environment end filter out the old
# PYTHONPATH variable if exists in the environment
env = [env for env in QtCore.QProcess.systemEnvironment()
       if not env.startswith('PYTHONPATH=')]
# Add your PYTHONPATH
env.append('PYTHONPATH=path_to_where_you_want')
# Create a process, set the environment and run the script
p = QtCore.QProcess()
p.setEnvironment(env)
p.start('perl abc.pl')

If you want the subprocess python to just revert to it's default PYTHONPATH just remove the current one from environment (skip the env.append part)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top