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

2019-08-27 21:04发布

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'))

2条回答
\"骚年 ilove
2楼-- · 2019-08-27 21:33

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.

查看更多
Viruses.
3楼-- · 2019-08-27 21:41

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.

查看更多
登录 后发表回答