如何将子流程调用传递到文本文件? [英] How do I pipe a subprocess call to a text file?

查看:67
本文介绍了如何将子流程调用传递到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"])

现在我有了运行的脚本.当我运行它并到达此行时,它开始打印内容,因为run.sh中有打印内容.

RIght now I have a script that I run. When I run it and it hits this line, it starts printing stuff because run.sh has prints in it.

我如何也将其通过管道传输到文本文件? (如果可能,还可以打印)

How do I pipe this to a text file also? (And also print, if possible)

推荐答案

如果要将输出写入文件,可以使用

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

需要Nonesubprocess.PIPE,文件对象或文件描述符.第一个是默认值,stdout是从父级继承的(您的脚本).第二个允许您从一个命令/进程到另一个命令/进程.第三和第四项是您想要的,将输出写入文件.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

您需要使用open之类的文件打开文件,并将对象或文件描述符整数传递给call:

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

我猜想任何有效的类似文件的对象都可以工作,就像套接字(gasp :)一样,但是我从未尝试过.

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

正如 marcog 在您可能还希望重定向stderr的注释中提到的那样,您可以将其重定向到同一位置作为stderr=subprocess.STDOUT的标准输出.上述任何一个值也可以使用,您可以重定向到其他位置.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

这篇关于如何将子流程调用传递到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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