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

How to get output of a script in a txt file python

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