[英]How to get the output from executing shell commands in Python
我正在嘗試使用python
執行此 shell 命令
但問題是,即使有錯誤,它也不會給出輸出:
這是我試過的:
get_ns_p1 = subprocess.Popen(['kubectl', 'get', 'ns'], stdout=subprocess.PIPE)
get_ns_p2 = subprocess.Popen(["grep", "-E", "\'(^|\s)"+NAMESPACE+"($|\s)\'"], stdin=get_ns_p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
get_ns_p1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out_ns, err = get_ns_p2.communicate()
print("output: " + out_ns)
print("error: " + err)
輸出看起來像:
輸出:
錯誤:
但在終端本身,它顯示如下輸出:
來自服務器的錯誤(AlreadyExists):命名空間“namespace-tests”已經存在
我怎么能把這個錯誤告訴我的err
變量?
您的代碼工作正常; 問題是如果kubectl
完全正確寫入,您正試圖捕獲在stderr
上發出的字符串。
然而,無論如何,將grep
作為一個單獨的子進程運行是非常低效和不必要的; Python 本身在re
庫中提供了一個功能更強大和更完整的正則表達式引擎,它還可以讓您避免啟動單獨進程的開銷。
import re
r = re.compile(r'(?:^|\s){}(?:\s|$)'.format(NAMESPACE))
kube = subprocess.run(['kubectl', 'get', 'ns'], text=True, capture_output=True)
e = []
for line in kube.stderr.split('\n'):
if r.search(err):
e.append(line)
err = '\n'.join(line)
如果您局限於沒有subprocess.run()
的舊版本 Python,則必須重新實現它,效果很差。
p = subprocess.Popen(['kubectl', 'get', 'ns'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_ns, err = p.communicate()
e = []
for line in err.split('\n'):
...
這有許多缺陷和缺點; 你真的應該認真考慮升級到 Python 3.5+。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.