Skip to content
Advertisement

Capture output from external command and write it to a file

I am trying to create a script that calls on a linux command from my Ubuntu server and prints the output of aforementioned command to txt files. This is literally the first script I’ve ever written, I just started learning python recently. I want 3 files in 3 separate folders with filenames unique to date.

def swo():
        from subprocess import call
        call("svn info svn://url")

def tco():
        from subprocess import call
        call("svn info svn://url2")

def fco():
        from subprocess import call
        call("url3")

import time
timestr = time.strftime("%Y%m%d")

fs = "/path/1/" + timestr
ft = "/path/2/" + timestr
fc = "/path/3/" + timestr


f1 = open(fs + '.txt', 'w')
f1.write(swo)
f1.close()

f2 = open(ft + '.txt', 'w')
f2.write(tco)
f2.close()

f3 = open(fc + '.txt' 'w')
f3.write(fco)
f3.close()

It is failing at the f.write() functions. I’m stuck at making the output of the linux commands the actual text in the new files.

Advertisement

Answer

I figured it out after all. The following works great!

## This will get the last revision number overall in repository ##

import os
sfo = os.popen("svn info svn://url1 | grep Revision")
sfo_output = sfo.read()
tco = os.popen("svn info svn://url2 | grep Revision")
tco_output = tco.read()
fco = os.popen("svn://url3 | grep Revision")
fco_output = fco.read()




## This part imports the time function, and creates a variable that will be the ##
## save path of the new file which is than output in the f1, f2 and f3 sections ##

import time
timestr = time.strftime("%Y%m%d")

fs = "/root/path/" + timestr
ft = "/root/path/" + timestr
fc = "/root/path/" + timestr

f1 = open(fs + '-code-rev.txt', 'w')
f1.write(sfo_output)
f1.close()

f2 = open(ft + '-code-rev.txt', 'w')
f2.write(tco_output)
f2.close()

f3 = open(fc + '-code-rev.txt', 'w')
f3.write(fco_output)
f3.close()
Advertisement