Skip to main content
 首页 » 编程设计

python之如何在 txt 文件 python 中获取脚本的输出

2025年02月15日8jyk

我正在尝试在 txt 文件中获取 shell 命令的输出。到目前为止,我已经成功地以这种方式获得了我的脚本的输出

import subprocess 
import logging 
logging.basicConfig(level=logging.DEBUG,filename='E:\FYP\FYPPP\AMAPT\hola.txt',filemode='w') 
console = logging.StreamHandler() 
console.setLevel(logging.INFO) 
formatter = logging.Formatter('') 
console.setFormatter(formatter) 
logging.getLogger('').addHandler(console)    
command="sh amapt.sh" 
 logging.info(subprocess.Popen(command,stdout=subprocess.PIPE,shell=True).stdout.read()) 

这会显示我的脚本 (amapt.sh) 的输出,并将输出存储在一个 txt 文件中。 但我必须获得“sh amapt.sh -s try.apk”的输出并将其存储在上面的 txt 文件中。我试过这样做

command="sh amapt.sh -s try.apk" 
     logging.info(subprocess.Popen(command,stdout=subprocess.PIPE,shell=True).stdout.read()) 

但是我在运行这段代码时遇到了这个错误

tput: terminal attributes: No such device or address 
 
tput: terminal attributes: No such device or address 

请您参考如下方法:

为什么不使用 subprocess.call ?您可以使用 stdout 参数定向到文件流。

from subprocess import call 
command = ['echo','Hello!'] 
call(command, stdout=open('output.txt','w'))