2013-12-17 28 views
0

我正在寫一個腳本,簡單地與交互式shell腳本進行交互,我偶然發現一個問題,與交互式shell腳本交互的子進程會結束,但然後掛起,當你擊中輸入時,它會跳過子進程運行後立即發出的raw_input()調用。Python的子進程中斷下面的raw_input

我的代碼看起來是這樣的:

#!/usr/bin/python 

import subprocess; 
import os; 
import sys; 
import time; 

# Set up constants 
GP_HOST = "1.1.1.1:5432"; 
GP_USER = "admin"; 
GP_PASS = "password"; 

PG_HOST = "2.2.2.2:5432"; 
PG_USER = "admin"; 
PG_PASS = "password"; 

# Collect required information from the user 
new_client_name = raw_input('New Client Name (Also DB Name): '); 
# Ensure there were no typos in the new client name 
name_okay = raw_input("Is the name '"+new_client_name+"' okay? (Y/N): "); 

while name_okay.upper() != "Y": 
     new_client_name = raw_input('New Client Name (Also DB Name): '); 
     name_okay = raw_input("Is the name '"+new_client_name+"' okay? (Y/N): "); 

# Start the interactive Database script, and create new Greenplum/PostgreSQL databases 
clone_child = subprocess.Popen(['/path/to/scripts/startBuilder.sh'], stdin=subprocess.PIPE, shell='true'); 
clone_child.stdin.write("connect greenplum "+GP_HOST+" "+GP_USER+" "+GP_PASS+"\n"); 
clone_child.stdin.write("create "+new_client_name+"\n"); 
clone_child.stdin.write("disconnect\n"); 
clone_child.stdin.write("connect postgresql "+PG_HOST+" "+PG_USER+" "+PG_PASS+"\n"); 
clone_child.stdin.write("create "+new_client_name+"\n"); 
clone_child.stdin.write("disconnect\n"); 
clone_child.stdin.write("exit\n"); 

# Flush out stdin, close the subprocess, and wait for the main program to resume 
clone_child.stdin.flush(); 

# Request the Client details needed to add the client to CEA 
auth_host = raw_input('Enter Authhost with Port: '); 

client_version = raw_input('Client Version to Create: '); 

clone_client = raw_input('Clone an existing client? (Y/n): '); 
... 

我曾試圖把clone_child.stdin.close();我沖洗通話後,它仍然掛起,並跳過第一raw_input()電話。

我想這只是一個難題,因爲我找不到與我的問題相同的任何其他問題,儘管我懷疑這可能是由於我如何解釋問題。

回答

0

我發現這個問題的答案最後,感謝這個鏈接:Writing to a python subprocess pipe

我加

clone_child.stdin.close(); 
clone_child.wait(); 

clone_child.stdin.flush();通話後。現在它正確地關閉了子進程。正如你所看到的,我還在clone_child.stdin.close()呼籲中加入了一個很好的措施。

希望這有助於下一個發現自己有這個問題的人。

+2

提示:Python在行尾沒有需要分號的地方。擁有它們對代碼沒有任何正面貢獻。 – iCodez

+0

啊,我其實知道這一點。我只是做了很多JS編碼,這是習慣。 – SamHuckaby