如何从 python 程序生成多个 python 脚本?
我想从我的程序中生成(fork?)多个Python脚本(也是用Python编写的)。
我的问题是我想为每个脚本分配一个终端,因为我将使用 pexpect
收集它们的输出。
我尝试过使用 pexpect
、os.execlp
和 os.forkpty
但它们都没有达到我的预期。
我想生成子进程并忘记它们(它们将处理一些数据,将输出写入终端,我可以使用 pexpect 读取该输出,然后退出)。
是否有任何图书馆/最佳实践/等。 完成这项工作?
ps 在你问为什么我要写入 STDOUT 并从中读取之前,我会说我不写入 STDOUT,我读取 tshark 的输出。
I want to spawn (fork?) multiple Python scripts from my program (written in Python as well).
My problem is that I want to dedicate one terminal to each script, because I'll gather their output using pexpect
.
I've tried using pexpect
, os.execlp
, and os.forkpty
but neither of them do as I expect.
I want to spawn the child processes and forget about them (they will process some data, write the output to the terminal which I could read with pexpect
and then exit).
Is there any library/best practice/etc. to accomplish this job?
p.s. Before you ask why I would write to STDOUT and read from it, I shall say that I don't write to STDOUT, I read the output of tshark
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅子流程模块
See the subprocess module
您想专用一个终端或一个 python shell?
您已经对 Popen 和 Subprocess 有了一些有用的答案,如果您已经计划使用 pexpect,也可以使用它。
根据需要创建任意数量的子级/shell,然后使用 child.before() 或 child.after() 来获取响应。
当然,您可能希望添加要发送的定义或类,而不是“mycommand1”,但这只是一个简单的示例。
如果你想在linux中制作一堆终端,你只需要替换pextpext.spawn行中的'python'即可。
注意:我还没有测试上面的代码。 我只是根据过去的经验来回答 pexpect。
You want to dedicate one terminal or one python shell?
You already have some useful answers for Popen and Subprocess, you could also use pexpect if you're already planning on using it anyways.
Make as many children/shells as you want and then use the child.before() or child.after() to get your responses.
Of course you would want to add definitions or classes to be sent instead of "mycommand1", but this is just a simple example.
If you wanted to make a bunch of terminals in linux, you just need to replace the 'python' in the pextpext.spawn line
Note: I haven't tested the above code. I'm just replying from past experience with pexpect.
我不明白为什么你需要期待这个。 tshark 应该将其输出发送到 stdout,并且只有出于某些奇怪的原因才会将其发送到 stderr。
因此,你想要的应该是:
I don't understand why you need expect for this.
tshark
should send its output to stdout, and only for some strange reason would it send it to stderr.Therefore, what you want should be:
从 Python 3.5 开始,您可以执行以下操作:
这也会自动重定向 stdout 和 stderr。
From Python 3.5 onwards you can do:
This also automatically redirects stdout and stderr.