python - Python如何阻止代码打印输出
问题描述
我正在使用 Ubuntu,并试图找出是否安装了 AIDE。到目前为止,这是我的代码。
import subprocess
result = subprocess.run(['dpkg', '-s', 'aide'], stdout = subprocess.PIPE)
print(result)
使用 subprocess.PIPE 后,执行的命令的输出仍然被打印到 python shell 上。
print(result) 给了我这个输出。
CompletedProcess(args=['dpkg', '-s', 'aide'], returncode=1, stdout=b'')
如何将执行的命令的输出放入变量中并仅在需要时打印?
解决方案
您可以使用 Popen:
import subprocess
process = subprocess.Popen(['dpkg', '-s', 'aide'], stdout=subprocess.PIPE)
output, _ = process.communicate()
... some code ...
print(output)
推荐阅读
- c# - 我可以在 URL 中使用格式字符串导航到网页,替换 URL 的指定部分吗?
- react-native - Expo RN:分离与弹出
- r - 将命令循环到整个目录
- spring-boot - 执行器/指标端点中的 Hystrix 指标 [spring-boot 2.0]
- android - 使用活动别名时Android构建失败
- android - 意图和 startActvity 如何在内部工作?
- javascript - 删除包含特定标签的标签父级
- bash - tcl 或 sed 或 shell 搜索替换多行
- javascript - 仅对特定元素应用 CssRules
- google-maps - 谷歌地图 api 计数