无法将命令的输出重定向到文件

Not able to redirect output of the command to a file

我的问题是在执行下面的代码后,我能够在 shell 中看到每个命令的输出。如何将 shell 输出到文件

我试过下面的方法,但它不起作用

python pr.py >> pr.txt

 import os

 f=open("pr1.txt","r")
 df=0
 for i in f:

     df=df+1
     if df==4:
        break
     print i
     os.system("udstask expireimage -image" + i)

每次执行 "os.system("udstask expireimage -image" + i)" 后都会显示文件的命令状态

您可以尝试类似的方法:

import os

f=open("pr1.txt","r")
 df=0
 for i in f:

     df=df+1
     if df==4:
        break
     print i
     os.system("udstask expireimage -image" + i + " > pr.txt")

它将命令的输出重定向到 pr.txt。

您应该使用 subprocess 而不是 os.system,后者具有更高效的流处理并在调用 shell 命令时为您提供更多控制:

import os
import subprocess

f=open("pr1.txt","r")
 df=0
 for i in f:

     df=df+1
     if df==4:
        break
     print i
     task = subprocess.Popen(["udstask expireimage -image" + i],stdout=subprocess.PIPE,shell=True)
     task_op = task.communicate()
     task.wait()

现在您的输出已存储在 task_op 中,您可以将其写入文件或执行任何您想做的事情。它是元组形式,你可能只需要写必填部分。