Search code examples
pythonwindowssubprocessenvironment-variablespopen

How to get environment from a subprocess?


I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?

This is what the program look like:

import subprocess

subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work

but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).

N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)


Solution

  • Since you're apparently in Windows, you need a Windows answer.

    Create a wrapper batch file, eg. "run_program.bat", and run both programs:

    @echo off
    call proc1.bat
    proc2
    

    The script will run and set its environment variables. Both scripts run in the same interpreter (cmd.exe instance), so the variables prog1.bat sets will be set when prog2 is executed.

    Not terribly pretty, but it'll work.

    (Unix people, you can do the same thing in a bash script: "source file.sh".)