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

时间:2017-07-24 22:15:06

标签: python shell logging subprocess popen

我试图在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

1 个答案:

答案 0 :(得分:1)

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

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