2012-09-05 46 views
0

我認爲這應該起作用。我想要得到這個命令的輸出 「grep -l%s * .py」%標籤爲每個標籤, 帶有標籤名稱的已創建文件。我在我的python腳本中做了什麼錯誤來獲取輸出?

import os 
import sys 

results_dir = '/home/ks/one/work/tn/format-description 15852/results' 
converters_dir = '/home/ks/one/work/cvr' 
export_dir = '/home/ks/one/work/epr' 
all_dirs = {'cvr':cvrs_dir, 
      'epr':eprs_dir} 

tags = [tag.strip() for tag in open('new file').readlines()] 
for coe, directory in all_dirs.items(): # coe - type of our file 
    os.chdir(results_dir) 
    for tag in tags: 
     tag_file = open(coe + ' ' + tag, 'w') 
     sys.stdout = tag_file 
     os.chdir(directory) 
     os.system("grep -l %s *.py" % tag) 
     tag_file.close() 

但是當腳本運行時我看到的全部內容 - 它在我的控制檯中輸出。

+2

考慮使用'subprocess'庫而不是'os.system'。 – Amber

回答

2

使用Python

的子模塊

http://docs.python.org/library/subprocess.html

文檔中含有大量的文檔和示例。

其他(差)選項以使用os.system()被重定向輸出到文件

os.system('do_something >/tmp/myoutput') 

再後來從內的Python讀取輸出文件。然而這很醜陋 並且可能不是很便攜。

0

我能想到的,所以你可以在蟒蛇的輸出得到最起碼的變化是改變:

os.system("grep -l %s *.py" % tag) 

爲:

output = commands.getoutput("grep -l %s *.py" % tag) 

這樣一來,命令的輸出將結束於輸出變量。

我不知道爲什麼其他人教條地告訴你改變你的代碼使用子進程;它需要更多的重寫才能完成。

+0

命令模塊已被棄用(並且不是可移植的afaik) –

+0

我認爲人們通過工作示例和/或解釋可以獲得更多幫助,即使該命令已被棄用。作爲子進程的常用用戶(以及其他做這些事情的方式),我可以告訴你,子進程文檔不是很清楚。問問你自己是否想幫助海報或是正確的? –