Python捕获终端输出

时间:2018-12-24 00:35:14

标签: python

嘿,我遇到了一个问题,那就是python如何像此命令一样捕获输出

os.system("apt install apt-transport-https") 

,然后如果已经安装了它以跳过它,以便不进行新安装?

2 个答案:

答案 0 :(得分:0)

尝试使用os.popensubprocess

from subprocess import Popen, PIPE

process = Popen(['apt', 'install', 'apt-transport-https'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)

stdout中捕获输出后,您可以在该字符串中搜索所需的结果。

答案 1 :(得分:0)

command = 'apt install apt-transport-https'
r = os.popen(command) #Execute command
info = r.readlines()  #read command output
for line in info:  #handle output line by line
    line = line.strip('\r\n')
    print line