简体   繁体   English

在python中使用subprocess.call时如何将stdout重定向到文件?

[英]How do I redirect stdout to a file when using subprocess.call in python?

I'm calling a python script (B) from another python script (A). 我从另一个python脚本(A)调用python脚本(B)。

Using subprocess.call, how do I redirect the stdout of B to a file that specify? 使用subprocess.call,如何将B的stdout重定向到指定的文件?

I'm using python 2.6.1. 我正在使用python 2.6.1。

Pass a file as the stdout parameter to subprocess.call : 将文件作为stdout参数传递给subprocess.call

with open('out-file.txt', 'w') as f:
    subprocess.call(['program'], stdout=f)

Alternate approach 替代方法

import subprocess
p=subprocess.Popen('lsblk -l|tee a.txt',stdout=subprocess.PIPE,shell=True)
(output,err)=p.communicate()
p_status=p.wait()
print output

Above code will write output of command to file a.txt 上面的代码会将命令输出写入文件a.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Python subprocess.call()时如何写入文件开头? - How to write to the beginning of a file when using Python subprocess.call()? 如何将Python的subprocess.call()输出重定向到文件? - How to redirect Python's subprocess.call() output to file? 当使用subprocess.call()时,如果使用非必需配置进行日志记录,如何设置它以将stdout重定向到日志文件的方式? - When using subprocess.call(), how to set it in way that redirects stdout to a log file if you are using the disctionary configuration for logging? 设置标准输出时,调用subprocess.call挂起 - Calling subprocess.call hangs when I set the stdout 如何将subprocess.call()输出推送到终端和文件? - How do I push a subprocess.call() output to terminal and file? 如何使用Python捕获subprocess.call错误? - How do I catch a subprocess.call error with Python? 使用subprocess.call执行python文件? - Using subprocess.call to execute python file? 为什么在使用subprocess.call()时,在此简单的Python-CGI上仍然出现错误500? - Why do I keep getting Error 500 on this simple Python-CGI when using subprocess.call()? Python:从subprocess.call捕获stdout - Python: Capture stdout from subprocess.call 使用subprocess.call()运行程序时,如何获取程序创建的日志文件? - How do I get the log file a program creates when running it with subprocess.call()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM