How can I spawn new shells to run Python scripts f

2019-01-11 03:05发布

问题:

I have successfully run several Python scripts, calling them from a base script using the subprocess module:

subprocess.popen([sys.executable, 'script.py'], shell=True)

However, each of these scripts executes some simulations (.exe files from a C++ application) that generate some output to the shell. All these outputs are written to the base shell from where I've launched those scripts. I'd like to generate a new shell for each script. I've tried to generate new shells using the shell=True attribute when calling subprocess.call (also tried with popen), but it doesn't work.

How do I get a new shell for each process generated with the subprocess.call?

I was reading the documentation about stdin and stdout as suggested by Spencer and found a flag the solved the problem: subprocess.CREATE_NEW_CONSOLE. Maybe redirecting the pipes does the job too, but this seems to be the simplest solution (at least for this specific problem). I've just tested it and worked perfectly:

subprocess.popen([sys.executable, 'script.py'], creationflags = subprocess.CREATE_NEW_CONSOLE)

回答1:

Popen already generates a sub process to handle things. You just need to redirect the output pipes. Look at the subprocess documentation, specifically the section on popen stdin, stdout and stderr redirection.

If you don't redirect these pipes, it inherits them from the parent. Just be careful about deadlocking your processes.

You wanted additional windows for each subprocess. This is handled as well. Look at the startupinfo section of subprocess. It explains what options to set on windows to spawn a new terminal for each subprocess. Note that it requires the use of the shell=True option.



回答2:

To open in a different console, do (tested on Windows 7 / Python 3):

from sys import executable
from subprocess import Popen, CREATE_NEW_CONSOLE

Popen([executable, 'script.py'], creationflags=CREATE_NEW_CONSOLE)

input('Enter to exit from this launcher script...')


回答3:

This doesn't actually answer your question. But I've had my problems with subprocess too, and pexpect turned out to be really helpful.