【问题标题】:timing and redirecting subprocess:PIPE output to file定时和重定向子进程:管道输出到文件
【发布时间】:2019-02-08 06:42:21
【问题描述】:

我正在尝试执行 bash,并希望将 shell 上的输出重定向到文件

这是我目前所拥有的

baby = subprocess.Popen('some command', stdout = subprocess.PIPE, shell = True)
print (baby.stdout.readlines()) #i wanna see it in console
with open("log.txt","a") as fobj: #wanna create a file log.txt and save the output there as string                                 
        fobj.write(stdout)

但我收到此错误NameError: name 'stdout' is not defined

我看过这些问题Run subprocess and print output to loggingsubprocess.Popen() doesn't redirect output to fileCan you make a python subprocess output stdout and stderr as usual, but also capture the output as a string?,但无济于事,它们对我来说都太复杂了,我迷失在所有代码中..

我不能将标准输出重定向到普通的 txt 文件吗? 有没有一种方法可以构建一个函数来计时该脚本的执行并将其放在同一个 log.txt 文件中(我使用time ./myscript.py 来花时间,但我也不知道如何将它重定向到txt 文件)

【问题讨论】:

    标签: python linux subprocess stdout timing


    【解决方案1】:

    你应该根据自己的需要调整这个例子

    首先创建 input.txt 文件

    然后

    import sys
    
    with open(sys.argv[1], 'r') as input, open(sys.argv[2], 'w') as output:
        for line in input:
            output.write(str(line.strip()) + '\n')
    

    你从命令行运行它(s4.py,你可以重命名它)

    python s4.py input.txt output.txt
    

    输出

    obama
    is
    my boss
    

    你可以猜测,但输出与输入相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-16
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多