Question : python os.popen

How can I use os.popen to run a system command like "ls" on a linux box and write the output into a file. I am trying to do something a bit more intelligent than this but my only holdback is getting the output of a system call into a file...

Can anyone give a simple example. I have tried something like below with no luck

name="test"
files = open(name, 'w')
a = os.popen("ls","w")
a.write("test")



Thanks for any help

Answer : python os.popen

above command will work.

however ls is executed by a shell subprocess.


The subprocess way would be:


1:
2:
3:
4:
5:
6:
7:
8:
from subprocess import Popen

name = 'test.txt'
outfile = open(name,'w')
command = [ 'ls','-l' ]
sub_proc = Popen(command,stdout=outfile)
sub_proc.wait() # wait till subprocess is finished
outfile.close()
Random Solutions  
 
programming4us programming4us