首页 > 解决方案 > subprocess.run().stdout.read() 返回 CompletedProcess 不是字符串

问题描述

subprocess用来获取命令行bitwarden工具的输出以将其重定向到albert(Linux 的启动器)。我在用着:

returned_user = subprocess.run(["bw", "get", "username", query, "--raw", "--session", session_key], text=True, stdout=subprocess.PIPE, shell=True, check=True).stdout.read()

检查type(returned_user)给出CompletedProcess。我如何获得stdout字符串?subprocess.check_output也返回 a CompletedProcess

一切都在 Python 3.9.1 中完成。

标签: python-3.xsubprocessstdout

解决方案


参考https://docs.python.org/3/library/subprocess.html,您在参数中错过了 capture_output=True 。我使用 python 3.7.3(在我的 beagelbone 上):

只需尝试 python shell:

>>> import subprocess
>>> command = "echo 123"  # your command here.
>>> result = subprocess.run(command, text=True, shell=True, check=True, capture_output=True)
>>> user = 'unknown'
>>> print (user)
unknown
>>> if result.returncode == 0:
...     user = result.stdout.strip()
... 
>>> print (user)
123
>>> 

最好的问候, 伯恩德


推荐阅读