在 python 子进程中保留 bash 重定向 [英] Preserving bash redirection in a python subprocess

查看:47
本文介绍了在 python 子进程中保留 bash 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我只允许使用 python 2.4.4

To begin with, I am only allowed to use python 2.4.4

我需要在 python 中编写一个进程控制器,它启动和各种子进程监控它们如何影响环境.这些子进程中的每一个本身都是 python 脚本.

I need to write a process controller in python which launches and various subprocesses monitors how they affect the environment. Each of these subprocesses are themselves python scripts.

当从 unix shell 执行时,命令行看起来像这样:

When executed from the unix shell, the command lines look something like this:

python myscript arg1 arg2 arg3 >output.log 2>err.log &

python myscript arg1 arg2 arg3 >output.log 2>err.log &

我对输入或输出不感兴趣,python不需要处理.python程序只需要知道1)每个进程的pid2)每个进程是否正在运行.

I am not interested in the input or the output, python does not need to process. The python program only needs to know 1) The pid of each process 2) Whether each process is running.

并且这些进程持续运行.

And the processes run continuously.

我尝试读取输出并再次将其发送出一个文件,但随后我遇到了 readline 不是异步的问题,对此有几个答案,其中许多答案非常复杂.

I have tried reading in the output and just sending it out a file again but then I run into issues with readline not being asynchronous, for which there are several answers many of them very complex.

如何制定一个保留 bash 重定向操作的 python 子进程调用?

How can I a formulate a python subprocess call that preserves the bash redirection operations?

谢谢

推荐答案

如果我正确理解您的问题,听起来您在这里寻找的是能够启动脚本列表并将输出重定向到文件.在这种情况下,请按如下方式启动您的每项任务:

If I understand your question correctly, it sounds like what you are looking for here is to be able to launch a list of scripts with the output redirected to files. In that case, launch each of your tasks something like this:

task = subprocess.Popen(['python', 'myscript', 'arg1', 'arg2', 'arg3'],
    stdout=open('output.log', 'w'), stderr=open('err.log', 'w'))

这样做意味着子进程的 stdout 和 stderr 被重定向到监控进程打开的文件,但监控进程不必参与复制数据.如果需要,您也可以重定向子进程标准输入.

Doing this means that the subprocess's stdout and stderr are redirected to files that the monitoring process opened, but the monitoring process does not have to be involved in copying data around. You can also redirect the subprocess stdins as well, if needed.

请注意,您可能希望处理错误情况等,而本示例中未处理这些情况.

Note that you'll likely want to handle error cases and such, which aren't handled in this example.

这篇关于在 python 子进程中保留 bash 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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