gpt4 book ai didi

python - 输出 os.popen() 的结果

转载 作者:行者123 更新时间:2023-11-28 22:41:04 25 4
gpt4 key购买 nike

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

关于python - 输出 os.popen() 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com