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