簡體   English   中英

子進程不捕獲 stdout 的輸出,將其存儲在 Python 中的變量中

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

我嘗試了下面的代碼來使用子進程從屏幕捕獲輸出,但它沒有做我打算做的事情。

#!/tools/bin/python

import subprocess

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

預期輸出為:

vimo 
vimo 

即一個用於回聲過程,一個用於打印結果輸出。 但我看到的是

vimo

但是當我嘗試打印結果輸出時,它總是空的。

我在上面的謎題中遺漏了什么!! 幫幫忙!!

在這里,您將大量剝離(並出於隱私原因進行更改)原始虛擬代碼段,從外部腳本輸出中獲取 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(使用 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