【问题标题】:How to get output of a script in a txt file python如何在txt文件python中获取脚本的输出
【发布时间】:2017-12-30 15:34:55
【问题描述】:

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

【问题讨论】:

  • sh amapt.sh -s try.apk > hola.txt 是否单独工作?即,在没有 python 的 shell 中?
  • amapt.sh 脚本正在调用tput 命令。如果脚本不是从终端运行,它可能会失败,例如,如果标准输入或标准输出是管道。
  • @Elmar peise 是的,它确实可以在没有 python 的情况下工作。它是一个 bash 脚本,我正在尝试在 python 中制作它的 UI。

标签: python shell logging subprocess popen


【解决方案1】:

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

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

【讨论】:

  • 哥们,你是个传奇!非常感谢
  • 很高兴我能帮上忙! subprocess.check_output 也很有用,它实际上与 subprocess.call 相同,除了调用发送到标准输出的内容由函数返回
猜你喜欢
  • 2010-10-19
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多