Thursday, November 29, 2007

Capturing shell output in Python

I need to capture the terminal text returned after I run some shell commands to create SVN repos. Unfortunately, os.system() doesn't capture the text, just the numeric value. Fortunately, Python has the command library. So now I can do this:

>>> import commands
>>> print(commands.getstatusoutput('ls -l'))
(0, 'total 0\ndrwxr-xr-x    9 dgreenfe  dgreenfe  306 Nov 28 19:02 bar\ndrwxr-xr-x   11 dgreenfe  dgreenfe  374 Nov 28 19:02 baz\ndrwxr-xr-x    9 dgreenfe  dgreenfe  306 Nov 28 19:00 foo\ndrwxr-xr-x   25 dgreenfe  dgreenfe  850 Nov 27 12:33 svn_bo11282007\ndrwxr-xr-x    9 dgreenfe  dgreenfe  306 Nov 29 10:37 tsvn1\ndrwxr-xr-x    9 dgreenfe  dgreenfe  306 Nov 29 10:46 tsvn2')

1 comment:

  1. Thanks! I was using subprocess before but this looks pretty much suitable for short shell commands.

    ReplyDelete

Note: Only a member of this blog may post a comment.