python子进程在raw_input之后中断

时间:2013-12-17 16:06:57

标签: python shell subprocess

我正在写一个简单地与交互式shell脚本交互的脚本,我偶然发现了一个问题,即与交互式shell脚本交互的子进程会结束然后挂起,当你按Enter键时,它会跳过在子进程运行后立即调用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()来电。

我认为这只是一个难以解决的问题,因为我找不到与我相同问题的任何其他问题,但我怀疑这可能是由于我如何处理这个问题。

1 个答案:

答案 0 :(得分:0)

我终于找到了答案,感谢这个链接:Writing to a python subprocess pipe

我添加了

clone_child.stdin.close();
clone_child.wait();
在我clone_child.stdin.flush();电话之后

。现在它正确地关闭了子进程。正如您所看到的,我还在clone_child.stdin.close()电话中添加了一个好的措施。

希望这有助于下一个发现自己的人。