2016-08-23 57 views
-3

我试图创建一个脚本,该脚本从我的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命令的输出成为新文件中的实际文本。

+0

'subprocess'通过将打开的文件对象传递给'call'函数的'stdout'参数,可以直接将命令输出写入文件。 https://docs.python.org/2/library/subprocess.html – FamousJameous

+0

你可能想从一个[Python教程]开始(https://docs.python.org/3.5/tutorial/)。你的函数没有返回一个(有用的)值,并且你不是首先调用它们。 ('tco()',而不是'tco')。 – chepner

+0

这就是我为什么在这里试火的原因。 –

回答

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

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

相关问题