输出 os.popen() 的结果

Ouputting the results of os.popen()

我正在尝试将 os.popen() 的结果发送到输出文件。这是我一直在尝试的代码

import os

cmd = 'dir'
fp = os.popen(cmd)
print(fp.read())  --Prints the results to the screen
res = fp.read()

fob = open('popen_output.txt','w')
fob.write(res)
fob.close()

fp.close()

输出文件只是空白。但是,命令的结果显示在屏幕上。我也试过像这样使用 Popen(根据子流程管理文档):

import subprocess

fob = Popen('dir',stdout='popen_output.txt',shell=true).stdout

以及:

import subprocess

subprocess.Popen('dir',stdout='popen_output.txt,shell=true)

将文件对象传递给标准输出而不是文件名作为字符串,您也可以使用 check_call 代替 Popen,这将引发 CalledProcessError 非零退出状态:

with open('popen_output.txt',"w") as f:
      subprocess.check_call('dir',stdout=f)

如果您在 windows subprocess.check_call('dir',stdout=f, shell=True),您也可以使用 > 使用 shell=True:

重定向
subprocess.check_call('dir > popen_output.txt',shell=True)

这似乎更符合您的意愿。您可以处理然后写入文件。

process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
for line in process.stdout:
    #processing then write line to file...
    file.write(line)

如果您不想处理,那么您可以在 subprocess 调用中进行处理。

subprocess.run('dir > popen_output.txt', shell=true)

好的。这让它开始了。感谢您的帮助!

fob = open('popen_output.txt','a')
subprocess.Popen('dir',stdout=fob,shell=True)
fob.close()

问题是您调用了两次 fp.read(),而不是将单个 fp.read() 调用的结果保存为 res、打印 res 并将 res 写入输出文件。文件句柄是有状态的,因此如果您对其调用两次读取,则第一次调用后的当前位置将位于 file/stream 的末尾,因此您的空白文件。

试试这个(只需提供相关更改):

fp = os.popen(cmd)
res = fp.read()
print(res)