python subprocess dd 和 stdout
我正在使用一个叫做subprocess的工具,通过unix的dd命令从/dev/random生成一个随机文件。现在,我想把dd命令的输出数据写入一个文件,而不是显示在屏幕上。以下是我使用的代码:
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
global out_fd
out_fd.write("executing the time dd command\n")
cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random', 'bs=1M' ,'count=5']
a = subprocess.Popen(cmd_list,stdout=out_fd)
a.wait()
if __name__ == '__main__':
os_system_dd()
这个代码没有把dd的输出写入文件,而是把它显示在了屏幕上。这是dd命令的特定功能吗?还是我对subprocess的使用有什么地方没搞明白?
2 个回答
2
之所以文件里什么都没有写,是因为信息被写到了错误输出(stderr)里。把错误输出重定向一下,你就能看到结果了。
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
global out_fd
out_fd.write("executing the time dd command\n")
cmd_list = ['date'] #Your list
a = subprocess.Popen(cmd_list,stdout=out_fd, stderr=out_fd)
a.wait()
if __name__ == '__main__':
os_system_dd()
另外,在写完“正在执行时间...”之后,要记得刷新一下缓冲区。
3
dd
这个命令会把它的调试信息输出到错误信息流(stderr),而不是标准输出流(stdout)。
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
out_fd.write("executing the time dd command\n")
cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random',
'bs=1M' ,'count=5']
a = subprocess.Popen(cmd_list,stderr=out_fd) # notice stderr
a.communicate()
if __name__ == '__main__':
os_system_dd()