2016-08-23 93 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將命令輸出直接保存到文件中。

相關問題