2016-02-19 125 views
0

我正在执行从python连接到外部服务器的程序。
如果用户未通过身份验证,程序会要求输入用户名和密码。第一行后杀死子进程

下面是子程序输出的外观:

Authentication Required 

Enter authorization information for "Web API" 

<username_prompt_here> 
<password_prompt_here> 

我要杀死子“身份验证要求”在打印后对的,但问题是,我的代码工作错误 - 子是要求凭据后用户提供它,子进程被终止。

这里是我的代码:

with subprocess.Popen(self.command, stdout=subprocess.PIPE, shell=True, bufsize=1, universal_newlines=True) as process: 
    for line in process.stdout: 
     if 'Authentication Required' in line: 
      print('No authentication') 
      process.kill() 
     print(line) 

我在做什么错?

+0

你能发布完整的代码吗?还是完成?我没有看到您提示用户输入用户名和密码的位置。 –

+0

我没有提示 - 子程序会这样做(查看attatched输出)。 – Djent

+0

并且您想在Authentication Required行后立即终止进程? –

回答

1

我在做什么错了?

您的代码就可以了(如果你想后'Authentication Required'线,无论其位置杀子)如果子进程刷新其标准输出缓冲的时间。见Python: read streaming input from subprocess.communicate()

所观察到的行为表明孩子使用块缓冲模式,因此你的父脚本看到'Authentication Required'线太晚或与process.kill()杀死外壳不杀它的后代(通过命令创建的进程) 。

要解决它:

  • 看你是否能够通过一个命令行参数,如--line-buffered(由grep接受),强制行缓冲模式
  • 或者看看是否stdbufunbufferscript实用程序在您的情况下工作
  • 或者提供一个伪tty来欺骗流程,使其认为它直接在终端中运行 - 它也可能强制线路缓冲模式。

见代码示例:


而且 - 并不总是我要杀了编程的,在第一行之后。只有当第一行是

假设块缓冲问题是固定的,杀子进程“需要验证”如果第一行包含Authentication Required

with Popen(shlex.split(command), 
      stdout=PIPE, bufsize=1, universal_newlines=True) as process: 
    first_line = next(process.stdout) 
    if 'Authentication Required' in first_line: 
     process.kill() 
    else: # whatever 
     print(first_line, end='') 
     for line in process.stdout: 
      print(line, end='') 

如果shell=True你的情况需要然后看How to terminate a python subprocess launched with shell=True