Python 输出os.popen()的结果

Python 输出os.popen()的结果,python,subprocess,Python,Subprocess,我正在尝试将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() 输出文件为空。然而,命令的结果显示在屏幕上。我也

我正在尝试将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

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

将文件对象传递给stdout而不是将文件名作为字符串,您还可以使用
check\u call
代替Popen,这将引发非零退出状态的
CalledProcessError

with open('popen_output.txt',"w") as f:
      subprocess.check_call('dir',stdout=f)
如果您在windows
子进程上。请检查调用('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.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写入输出文件。文件句柄是有状态的,因此如果对其调用两次read,则第一次调用后的当前位置将位于文件/流的末尾,因此为空文件

尝试以下方法(仅提供相关更改):


你应该接受答案,而不是张贴你的工作代码。您应该进一步了解Padraic答案的要素。
fob = open('popen_output.txt','a')
subprocess.Popen('dir',stdout=fob,shell=True)
fob.close()
fp = os.popen(cmd)
res = fp.read()
print(res)