如何通过管道将子进程调用传递给文本文件? [英] How do I pipe a subprocess call to a text file?
问题描述
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)
推荐答案
如果要将输出写入文件,可以使用 stdout - subprocess.call
的参数.
If you want to write the output to a file you can use the stdout-argument of subprocess.call
.
两者都需要
None
(默认,stdout 继承自父级(你的脚本))subprocess.PIPE
(允许您从一个命令/进程管道到另一个)- 一个文件对象或一个文件描述符(你想要什么,将输出写入文件)
None
(the default, stdout is inherited from the parent (your script))subprocess.PIPE
(allows you to pipe from one command/process to another)- a file object or a file descriptor (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)
我猜任何有效的类似文件的对象都可以工作,比如套接字(喘气:)),但我从未尝试过.
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屋!