How to save data coming from "sudo dpkg -l" in an Ubuntu terminal using python

How to save data coming from "sudo dpkg -l" in an Ubuntu terminal using python, I tried to do it this way, but it does not work.

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

Use subprocess.check_output() to write the result of another process:

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

os.system() returns only the exit status of another process. The above example assumes sudo will not ask for a password.

+6
source

To save the output of a command to a file, you can 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 used to redirect stderr commands to stdout.

+1
source

Source: https://habr.com/ru/post/955555/


All Articles