如何通过管道将子进程调用传输到文本文件?
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
现在我有一个可以运行的脚本。当我运行它并且它到达这一行时,它开始打印内容,因为 run.sh 中有打印内容。
我如何将其也传输到文本文件? (如果可能的话,也可以打印)
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果要将输出写入文件,可以使用 stdout -
subprocess.call
的参数。它采用
None
(默认情况下,stdout 是从父级(您的脚本)继承的)subprocess.PIPE
(允许您从一个命令/进程通过管道传输到另一个命令/进程您需要使用
open
之类的命令打开文件,并将对象或文件描述符整数传递给call
:我猜任何有效的类似文件的对象都可以工作,比如套接字(喘气:)),但我从未尝试过。
正如 marcog 在评论中提到的,您可能也想重定向 stderr,您可以将其重定向到与 stdout 相同的位置
stderr=subprocess.STDOUT
。上述任何值都可以,您可以重定向到不同的位置。If you want to write the output to a file you can use the stdout-argument of
subprocess.call
.It takes either
None
(the default, stdout is inherited from the parent (your script))subprocess.PIPE
(allows you to pipe from one command/process to another)You need to open a file with something like
open
and pass the object or file descriptor integer tocall
:I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.
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.popen
的选项可以在call
中使用,所以...
然后你可以用
myoutput
做你想做的事情此外,你还可以做一些更接近的事情像这样的管道输出。
将会是:
python 手册页上有很多可爱、有用的信息。
The options for
popen
can be used incall
So...
Then you can do what you want with
myoutput
Also, you can do something closer to a piped output like this.
would be:
There's plenty of lovely, useful info on the python manual page.