如何从基础 Python 脚本生成新的 shell 以运行 Python 脚本? [英] How can I spawn new shells to run Python scripts from a base Python script?

查看:40
本文介绍了如何从基础 Python 脚本生成新的 shell 以运行 Python 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功运行了几个 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 的部分和 stderr 重定向.

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.

这篇关于如何从基础 Python 脚本生成新的 shell 以运行 Python 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆