[英]How to store subprocess call output to a file python
i have a script in bash that i am running in python using call from subprocess. 我在bash中有一个脚本,我正在使用子进程的调用在python中运行。 i want the script output (strings) to be stored in a file.
我希望将脚本输出(字符串)存储在文件中。 i tried working on a code that is
我尝试过的代码是
import logging
logging.basicConfig(level=logging.DEBUG,
format='',
datefmt='',
filename='E:\FYP\FYPPP\AMAPT\log.txt',
filemode='w')=
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.info(call("sh amapt.sh", shell=True))
logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')
logger1.debug('test.')
logger1.info('test1.')
logger2.warning('test2.')
logger2.error('test3.')
But displays the output as an integer of my script. 但是将输出显示为我的脚本的整数。 check the image here I want the yellow/green output text to be stored in file but it is storing 255 instead of this text from my script.
在这里检查图像, 我希望将黄色/绿色输出文本存储在文件中,但它存储的是255,而不是脚本中的文本。
Guide me please. 请引导我。
call
returns the return code of your script. call
返回脚本的返回码。 You need to get the output of the process: 您需要获取流程的输出 :
logging.info(check_output("sh amapt.sh"))
notes: 笔记:
shell=True
shell=True
To get the output no matter what you could use Popen
instead for instance like this: 为了获得输出,无论您使用诸如以下示例的
Popen
都可以:
logging.info(Popen("sh amapt.sh",stdout=PIPE,stderr=STDOUT).stdout.read())
The added ,stderr=STDOUT
allows to get standard error in the log as well. 添加的
,stderr=STDOUT
允许在日志中获取标准错误。
or from python 3.5 you can use subprocess.run() instead of Popen
或从python 3.5您可以使用subprocess.run()代替
Popen
logging.info(run("sh amapt.sh",stdout=PIPE,stderr=STDOUT).stdout.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.