我已经成功运行了几个 Python 脚本,使用 subprocess 模块从基本脚本调用它们:
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)
但是,这些脚本中的每一个都会执行一些模拟(来自 C++ 应用程序的 .exe 文件),这些模拟会向 shell 生成一些输出.所有这些输出都写入我启动这些脚本的基础 shell.我想为每个脚本生成一个新的 shell.我尝试在调用 subprocess.call 时使用 shell=True
属性生成新的 shell(也尝试使用 popen),但它不起作用.
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.
如何为 subprocess.call 生成的每个进程获取一个新的 shell?
How do I get a new shell for each process generated with the subprocess.call?
我正在阅读 Spencer 建议的有关 stdin 和 stdout 的文档,并找到了解决问题的标志:subprocess.CREATE_NEW_CONSOLE.也许重定向管道也可以完成这项工作,但这似乎是最简单的解决方案(至少对于这个特定问题).我刚刚对其进行了测试并且运行良好:
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)
Popen 已经生成了一个子进程来处理事情.您只需要重定向输出管道.查看 subprocess 文档,特别是关于 popen stdin、stdout 的部分和标准错误重定向.
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.
您希望每个子进程都有额外的窗口.这也是处理的.查看子进程的 startupinfo 部分.它解释了在 Windows 上设置哪些选项来为每个子进程生成一个新终端.请注意,它需要使用 shell=True 选项.
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.
这篇关于如何生成新的 shell 以从基本 Python 脚本运行 Python 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!