0

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'))
Eevee
  • 47,412
  • 11
  • 95
  • 127
ShuSon
  • 407
  • 5
  • 10

2 Answers2

7

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thank you very much for the quick reply, I am trying it :XD – ShuSon Feb 16 '13 at 15:57
  • If you need interaction with the command, try http://pypi.python.org/pypi/pexpect – f13o Feb 16 '13 at 19:22
  • how do your code create `'/tmp/dpkg.txt'` file? – jfs Feb 17 '13 at 11:31
  • @J.F.Sebastian: It doesn't; the OP already knows how to do that. It was not part of the problem. – Martijn Pieters Feb 17 '13 at 11:31
  • @MartijnPieters: why do you want to load all the command output into the memory as a string only to write it back to a file immediately? Isn't it simpler (and more efficient in general) just to redirect to a file directly? – jfs Feb 17 '13 at 11:41
  • @J.F.Sebastian: It could very well be, but that's not what was being asked. :-) – Martijn Pieters Feb 17 '13 at 11:43
  • @MartijnPieters: The non-working code in the question `f.write(os.system('sudo dpkg -l'))` communicates the intent clearly: "write to a file the output of the command". – jfs Feb 17 '13 at 11:49
  • @J.F.Sebastian: Yet that version would also read the contents into memory. I agree that redirecting the output straight to the output file is a better idea all along. – Martijn Pieters Feb 17 '13 at 12:03
1

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670