2013-04-09 61 views
0

我想寫一個啓動子進程的python腳本,並寫入子進程標準輸入。對輸出進行一些測試,然後將更多命令寫入標準輸入。寫入標準輸入,訪問被拒絕

我曾嘗試:

def get_band(): 
    print "band" 
    p = subprocess.Popen(["/path/to/program","-c","-"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) 

    ran_stdout = p.communicate(input='show status')[0] 
    print(ran_stdout) 

然而print語句給出:

Unable to connect at 127.0.0.1, Connection refused. 

我在想,如果我這樣做對嗎?這裏是關於我試圖運行的過程的文檔。我想用最後一個選項。

Running the tool from the Linux shell allows additional options, depending on the options given to the command. The options are as follows: 

-h Displays help about the command 

-c <Filename> Instead of taking typed commands interactively from a user the commands are read from the named file, i.e. in batch mode. When all commands are processed the CLI session ends automatically. 

-c - As above but reads command from Linux stdin. This allows commands to be ‘piped’ to the program. 
+3

消息是否可以由子進程生成? – Bogdacutu 2013-04-09 16:15:03

+0

是的,謝謝你,我想知道爲什麼會這樣以及如何獲得許可?如果我使用這些參數從終端運行進程,它運行良好。 – Paul 2013-04-09 16:19:33

回答

1

如果您可以告訴我們關於該程序的更多信息,也許有人知道這個程序可以嘗試更好地解釋它是如何工作的。

不過,你描述

啓動子,並寫入到子標準輸入。對輸出進行一些測試,然後將更多命令寫入標準輸入。

與您的代碼不符。

你的代碼打印一些東西給我們自己的stdout,顯示band,然後與子進程進行「一次性」通信。

爲了清楚起見,p.communicate()寫入了子進程的所有內容,關閉它的stdin並讀出從stdout和stderr得到的所有內容。

因此它與您的願望不符:寫,讀,寫再次。

所以你必須自己製作。

如果您編寫的塊足夠小以保證適合管道緩衝區,那很簡單:只需編寫命令(不要忘記尾部\n)並讀取。

但請注意!不要讀得比你真正擁有的更多,否則你的閱讀可能會受阻。

因此,使用非阻塞IO或使用select.select()

如果您需要更多關於這個或其他的信息,還有其他的答案在這裏涵蓋這些主題。有一天我寫了one which might help you

+0

以下我認爲我的解決方案非常簡單。 – Paul 2013-04-10 10:50:14

0

由於某種原因,這個工作方式在同一行傳入命令。然後爲每個我想要的命令調用這個函數。

p = subprocess.Popen(["/path/to/program", '-c', '-', cmd_here], 
    stdout=subprocess.PIPE) 
    proc_stdout, proc_stderr = proc.communicate() 
    proc.wait() 
    #print stuff 
+0

如果你在cmdline上給cmd,可能你甚至可以省略'-c','-''。這取決於被調用的程序。除此之外,如果您對每個發出的命令都有單獨的子進程是可以的,那麼這可能是最簡單的解決方案。 – glglgl 2013-04-10 11:20:38

+0

所有權利感謝,仍然接受你的偉大答案:)是的,這是好的,現在我只需要在後臺運行它們,因爲一些輸出需要10分鐘才能發生。 – Paul 2013-04-10 11:22:27