tags:

views:

30

answers:

2

I call .bat files in Python to set system environments, and check the system environments were set properly, and then back to run python code, the system environments are changed back to original. How can I solve this problem?

I really appreciate any clues/answers

Thanks in advanced

+1  A: 

Environment settings always happen in the child process and never directly affect the parent process. However you can run (in the same child process that has changed its environment, at the very end of that process) a command (env in Unix-like environment, I believe set in DOS where .bat files lived and in Windows where .cmd files are similar) that outputs the environment to its standard-output, or to a file; the parent process can read that file and apply the changes to its own environment.

In Unix, subprocess.Popen('thescript; env', shell=True, stdout=...) may suffice. In Windows, I'm not sure passing as the first argument foo.bat; set would work; if it doesn't, just create a tiny temporary "auxiliary bat" that does foo.bat then set, and run that one instead.

Alex Martelli
A: 

I suspect that you are calling the batch file from the Python program and then returning to the calling Python code. A child process - in this case your call to the batch file - does not affect the environment of the parent process (your batch file).

Batch files that set up an environment are usually written as:

# set up my environment 
python myprogram.py

In this case the subordinate Python program will inherit the environment of the calling batch file.

msw