从外部命令捕获输出并将其写入文件

时间:2016-08-23 16:07:38

标签: python linux ubuntu svn scripting

我正在尝试创建一个脚本,该脚本从我的Ubuntu服务器调用linux命令,并将上述命令的输出打印到txt文件。这是我写过的第一个脚本,我刚开始学习python。我希望在3个独立的文件夹中有3个文件,文件名是日期唯一的。

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()

f.write()函数失败了。我坚持让linux命令的输出成为新文件中的实际文本。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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

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


f1 = open(fs + '.txt', 'w')
rc = sp.call("svn info svn://url", stdout=f1, stderr=sp.STDOUT)
f1.close()

f2 = open(ft + '.txt', 'w')
rc = sp.call("svn info svn://url2", stdout=f2, stderr=sp.STDOUT)
f2.close()

f3 = open(fc + '.txt' 'w')
rc = sp.call("svn info svn://url3", stdout=f3, stderr=sp.STDOUT)
f3.close()

假设您使用的url3命令应该是svn info svn://url3。这允许subprocess.call将命令输出直接保存到文件中。

答案 1 :(得分:0)

毕竟我想通了。以下工作很棒!

## 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()