【问题标题】:how to print subprocess' stdout directly to file如何将子进程的标准输出直接打印到文件
【发布时间】:2014-03-25 16:47:51
【问题描述】:

如何强制 subprocess.Popen/os.Popen 将大输出直接写入文件,而不在缓冲区中保存任何内容? 我试过这个:

os.popen(cmd, bufsize=0)

它没有帮助。 读取所有输出(同样是大输出)并将其保存到文件/列表的任何解决方案都会有所帮助。

【问题讨论】:

    标签: python python-2.7 subprocess popen


    【解决方案1】:

    您可以使用stdout 参数将输出从子进程重定向到文件:

    import shlex
    from subprocess import check_call
    
    with open('outputfilename', 'wb', 0) as outputfile:
        check_call(shlex.split(cmd), stdout=outputfile)
    

    你知道我应该在命令中添加什么以防止子进程将警告/错误打印到 shell 吗?

    只需设置stderr=subprocess.STDOUT 即可合并标准输出/标准错误。或将stderr 重定向到os.devnull 以丢弃输出。

    【讨论】:

    • 这有帮助!但shlex.split(cmd) 错了。我用字符串 cmd (cmd = "ls dir") 改变了它,它工作了。谢谢。你知道我应该在命令中添加什么来防止子进程向 shell 打印警告/错误吗?
    • 不,check_call("ls dir", stdout=outputfile) 失败。你想要shlex.split("ls dir") == ["ls", "dir"]。除非您需要,否则不要使用shell=True。提供明确的列表参数。 Here's why
    • raise child_exception OSError: [Errno 2] No such file or directory 这是我给它一个列表时得到的。
    • cmd = command.split(" ")check_call(cmd, stdout=outputfile)第二行
    • 使用 shlex.split() 没有帮助。该命令正在调用另一个脚本。
    【解决方案2】:

    这是将stdout重定向到文件的方法:

    import sys
    sys.stdout = open('your_file', 'w')
    

    然后将在 shell 中输出的所有内容都转储到该文件中。

    【讨论】:

    • 它没有用。该过程正在将约 500 行打印到文件中,并将其余行保存在缓冲区中。当我杀死脚本时,它将其余部分写入文件。
    • 你可以用写模式重新打开stdout文件描述符,0作为缓冲区大小(所以没有缓冲)。 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0).
    • 替换 sys.stdout 不会将子进程的输出重定向到文件。您需要使用子进程的stdout 参数或redirect stdout at file descriptor level, see stdout_redirected()
    猜你喜欢
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2018-02-25
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多