【问题标题】:python subprocess dd and stdoutpython子进程dd和stdout
【发布时间】:2011-09-28 10:20:52
【问题描述】:

我正在使用 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 命令的特定功能吗?还是我错过了一些关于子流程如何工作的东西?

【问题讨论】:

  • +1 用于简洁的代码并使用列表来构造参数。但是,我无法在这里重现您的问题;你的代码工作正常。如果整个代码是subprocess.Popen(['time','dd','if=/dev/random', 'of=sys_entropy_random', 'bs=1M' ,'count=5']).communicate(),你的问题还会出现吗?
  • 好吧,我试过这个code a = subprocess.Popen(['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random' , 'bs=1M' ,'count=5'],stdout=out_fd) code 仍然得到同样的错误。使用communicate() 可以解决我的问题,但我试图避免来自python 的额外显式写入。不过会尝试更新它。
  • 糟糕,我误解了这个问题。已回答 - 只需重定向 stderr 而不是 stdout。

标签: python subprocess dd


【解决方案1】:

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()

【讨论】:

    【解决方案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()
    

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

    【讨论】:

    • shell=True 只会让代码运行得更慢,更容易出错。为什么要使用它?
    • 我的错。我尝试添加不同的东西直到它起作用。现在我意识到除了 stderr 重定向之外,他的代码没有任何问题。更新我的答案以反映这一点。
    • @phihag 我认为这种放缓并不明显。如果命令行是硬编码的,shell=True 没有任何问题(除了它会留下一点难闻的气味)。如果它是一个动态的字符串,那确实是犯罪......
    猜你喜欢
    • 2018-09-20
    • 1970-01-01
    • 2011-07-07
    • 2021-06-02
    • 2020-05-13
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多