2014-03-24 48 views
0

我正在使用用Python編寫的腳本,它使用argparse模塊從命令行獲取它的參數。我試圖儘可能少地修改這個文件,因爲不同的人都在使用它。從另一個python腳本調用面向命令行的腳本

例:腳本稱爲CLscript.py和我一起

python CLscript.py -option1 arg1 -flag1 -option2 arg2 

叫它但我面對的,我想自動化的事情之一水平,並自動與廣泛的啓動此腳本的情況下腳本生成的參數。

我想繼續使用此腳本中可用的所有選項和標誌的現有組織。

例如,當我從topLevelScript.py貫穿CLscript.py:

subprocess.call("python CLscript.py -option1 arg1 -flag1 -option2 arg2") 

,我是從輸出事情錯看,我停止執行topLevelScript.py,但CLscript。 py繼續在另一個需要手動殺死的python進程中獨立運行。我不能在調試模式下啓動topLevelScript.py以停止CLscript.py中的斷點。

我想在python裏面做所有這些,而不用建立一個命令行字符串並用子進程啓動CLscript.py。 每次調用都將保持與原始啓動相同,就像函數調用一樣,不會像創建subprocess.call()一樣創建多個python線程。

有點像傳遞一個字符串列表的選項,標誌和參數莫名其妙的腳本也許?

有什麼樣

import CLscript.py 
CLsimulator(CLscript,["-option1",arg1,"-flag1","-option2",arg2]) 
+0

「創建多個python線程就像使用subprocess.call()」 - 「subprocess」模塊與線程無關。 – ElmoVanKielmo

+0

其實我不是很清楚你想要做什麼,請你詳細說明一下還是舉個例子? – lowitty

+1

「類似於傳遞帶有選項,標誌和參數的字符串列表」 - 「subprocess.call()」的第一個參數是字符串列表。 – ElmoVanKielmo

回答

1

首先,使用http://docs.python.org/2/library/subprocess.html#subprocess.Popen而不是subprocess.call()

import subprocess 

child = subprocess.Popen(
    ['python', 'CLscript.py', '-option1', 'arg1', '-flag1', '-option2', 'arg2'], 
    stdin=subprocess.PIPE, 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE 
) 

請注意,作爲第一個參數傳遞,就像你想要一個array of strings。其次,標準文件描述符的重定向將很重要。見http://docs.python.org/2/library/subprocess.html#subprocess.PIPE
現在你有child變量,它持有Popen類的實例。
你可以用這個實例做什麼?

# Check if child is terminated and possibly get the returncode 
child.poll() 
# Write to child's standard input by a file-like object accessible with 
child.stdin 
# Read child's standard output and standard error by file-like objects accesible with 
child.stdout 
child.stderr 

你說你想檢測是否在子進程中出現錯誤,從它的輸出。
您是否發現stdoutstderr對這種情況非常有用?
現在你想要終止孩子,如果你發現出了問題。

child.kill() 
child.terminate() 
child.send_signal(signal) 

如果你到底相信,一切都很順利,但你不想讓孩子完成通常,你應該使用

child.wait() 

甚至更​​好

child.communicate() 

因爲communicate會正確處理大量輸出。

祝你好運!

+0

好吧,我想在Popen之前作爲一些低級別的東西,我不應該使用call來代替,但是這樣看起來並不複雜。謝謝! –

+1

@antoine'subprocess.call(...)'實際上是'child = subprocess.Popen(...)'的簡寫,沒有管道到標準輸入,標準輸出,標準錯誤,後跟'child.wait()'。 – ElmoVanKielmo

1

會是這樣的工作?將大部分代碼提取到一個新的函數中,該函數的參數類似於您通過命令行發送的參數。然後編寫採集命令行參數,並將它們發送到第一功能的新功能...

def main(foo, bar): 
    a = foo + bar 
    print a 

def from_command_line(): 
    foo, bar = get_command_line_args() 
    main(foo, bar) 

if __name__ == "__main__": 
    from_command_line() 

然後其它腳本可以只調用的主要功能。

+0

這將是一個整潔的方式來處理問題,我喜歡這個想法,謝謝。不過就我個人而言,因爲這是一個合作項目,所以我不能修改這個文件,Elmo的回答允許我這樣做。 –

相關問題