简体   繁体   English

子进程不捕获 stdout 的输出,将其存储在 Python 中的变量中

[英]Subprocess not capturing the output of stdout storing it inside a variable in Python

I tried the below code to capture the output from screen using the sub-process, but its not doing what I intended to do.我尝试了下面的代码来使用子进程从屏幕捕获输出,但它没有做我打算做的事情。

#!/tools/bin/python

import subprocess

result = subprocess.check_output("echo $USERNAME", shell=True)
print result

expected output is:预期输出为:

vimo 
vimo 

ie one for the echo process and one for printing the result output.即一个用于回声过程,一个用于打印结果输出。 But what I see is但我看到的是

vimo

But when I try to print the result output, its always empty.但是当我尝试打印结果输出时,它总是空的。

What am I missing in the above puzzle !!我在上面的谜题中遗漏了什么!! Help out !!帮帮忙!!

Here you goes some greatly stripped (and altered for privacy reasons) raw dummy piece of code, grabbing both stdin and stdout from external script output.在这里,您将大量剥离(并出于隐私原因进行更改)原始虚拟代码段,从外部脚本输出中获取 stdin 和 stdout。

from subprocess import Popen, PIPE

cmd = ['echo', 'foo']

proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
comm = proc.communicate()

if proc.returncode != 0:
    # code to handle / parse stderr (comm[1])
    raise RuntimeError(
        '\'%s\': command has failed (%d):\n%s'
        % ('some value', proc.returncode, comm[1]))

for line in comm[0].split('\n'):
    if line.find('Wrote:') == 0:
        # some code to parse stdout
        pass

Python >= 3.7 (tested with Python 3.9) Python >= 3.7(使用 Python 3.9 测试)


r=subprocess.run(['echo','$XDG_DATA_HOME'],capture_output=True,shell=True)
assert r.stdout.find(b'share')>0 # ERROR
r=subprocess.run('echo $XDG_DATA_HOME',capture_output=True,shell=True)
assert r.stdout.find(b'share')>0 # OK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM