【问题标题】:python child process breaks following raw_inputpython子进程在raw_input之后中断
【发布时间】:2013-12-17 16:06:56
【问题描述】:

我正在编写一个与交互式 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() 调用。

我想这只是一个难以表达的问题,因为我找不到与我相同问题的任何其他问题,尽管我怀疑这可能是由于我如何表达问题。

【问题讨论】:

    标签: python shell subprocess


    【解决方案1】:

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

    我加了

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

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

    希望这可以帮助下一个遇到此问题的人。

    【讨论】:

    • 提示:Python 不需要在行尾使用分号。拥有它们不会对代码产生任何积极影响。
    • 啊,我其实知道这一点。我只是做了很多JS编码,这是习惯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多