2

我正在使用 subprocess 从 /dev/random 使用 unix dd 创建一个随机文件。现在,如果我希望将 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 命令的特定功能吗?或者我错过了一些关于子流程如何工作的东西?

4

2 回答 2

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()
于 2011-09-28T10:35:29.290 回答
2

文件中没有写入任何内容的原因是因为它已写入 stderr。重定向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()

此外,在写入“执行时间......”后刷新缓冲区

于 2011-09-28T10:31:40.930 回答