How to save the data coming from “sudo dpkg -l” in

2019-08-27 21:28发布

问题:

How to save the data coming from "sudo dpkg -l" in Ubuntu terminal by using python, I tried to do it this way, but it doesn't work

import os
f = open('/tmp/dpgk.txt','w')
f.write(os.system('sudo dpkg -l'))

回答1:

Use subprocess.check_output() to capture the output of another process:

import subprocess

output = subprocess.check_output(['sudo', 'dpkg', '-l'])

os.system() only returns the exit status of another process. The above example presumes that sudo is not going to prompt for a password.



回答2:

To save the output of a command to a file, you could use subprocess.check_call():

from subprocess import STDOUT, check_call

with open("/tmp/dpkg.txt", "wb") as file:
    check_call(["sudo", "dpkg", "-l"], stdout=file, stderr=STDOUT)

stderr=STDOUT is used to redirect the stderr of the command to stdout.