[Tutor] using subprocess to export files in bash
David Abbott
david at pythontoo.com
Tue May 8 20:06:03 CEST 2012
On Tue, May 8, 2012 at 1:41 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 08/05/12 15:18, Rogelio wrote:
>>
>> While reading the subprocess documentation, I found a great example on
>> how to call commands with a PIPE
>>
>> http://docs.python.org/library/subprocess.html
>>
>> **************************
>> output=`dmesg | grep hda`
>> # becomes
>> p1 = Popen(["dmesg"], stdout=PIPE)
>> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
>> p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
>> output = p2.communicate()[0]
>>
>> ****************************
>>
>> How do I do this and output to a file?
>
>
> Have you tried defining stdout in the second command to be a file?
>
> log = open('log.txt','w')
> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=log)
> ...
> log.close()
>
> I haven't tried but I think that should work...
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
I have used this before;
def uptime_report():
"""Generate uptime"""
p = subprocess.Popen("uptime > /tmp/uptime.txt",
shell=True, stdout=subprocess.PIPE)
return p.stdout.readlines()
That was from python 2.6
More information about the Tutor
mailing list