views:

269

answers:

3

I have a python script the runs this code:

strpath = "sudo svnadmin create /svn/repos/" + short_name
os.popen (strpath, 'w')

How can I get the output of that command stored in a variable or written to a log file in the current directory?

I know, there may not be an output, but if there is, I need to know.

A: 

you can do it in your bash-part:

strpath = "sudo svnadmin create /svn/repos/" + short_name + ' > log.txt'
SilentGhost
+1  A: 

If you don't need to write to the command, then just change the 'w' to 'r':

strpath = "sudo svnadmin create /svn/repos/" + short_name
output = os.popen (strpath, 'r')

for line in output.readlines():
    # do stuff

Alternatively if you don't want to process line-by-line:

strpath = "sudo svnadmin create /svn/repos/" + short_name
output = os.popen (strpath, 'r')

outtext = output.read()

However, I'd echo Greg's suggestion of looking at the subprocess module instead.

Amber
Thank you DAV for pointing out the r
shaiss
+3  A: 

Use the 'r' mode to open the pipe instead:

f = os.popen (strpath, 'r')
for line in f:
    print line
f.close()

See the documentation for os.popen() for more information.

The subprocess module is a better way to execute external commands like this, because it allows much more control over the process execution, as well as providing access to both input and output streams simultaneously.

Greg Hewgill
Thank you Greg for the post!
shaiss