首页 > 解决方案 > 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'')

如何将执行的命令的输出放入变量中并仅在需要时打印?

标签: python

解决方案


您可以使用 Popen:

import subprocess
process = subprocess.Popen(['dpkg', '-s', 'aide'], stdout=subprocess.PIPE)
output, _ = process.communicate()

... some code ...

print(output)

推荐阅读