2013-01-21 73 views
5

我很努力地在python中使用子进程。这是我的任务:在子进程中使用python Popen

  1. 开始通过命令行的API(这应该是不低于运行在命令行上任何参数不同)
  2. 验证我的API已经上来了。做到这一点的最简单方法是将标准轮询出来。
  3. 针对API运行命令。
    1:当我能够运行一个新的命令
  4. 通过查询验证命令完成的标准输出(API不支持日志记录)

什么我迄今试图将出现一个命令提示符我在这里用Popen卡住了。据我所知,如果我使用 subprocess.call("put command here")这个工程。我想尝试使用类似的东西:

import subprocess 

def run_command(command): 
    p = subprocess.Popen(command, shell=True, 
         stdout=subprocess.PIPE, 
         stderr=subprocess.STDOUT) 

,我使用run_command("insert command here")但什么都不做。

相对于2.我想答案应该类似于此: Running shell command from Python and capturing the output, 但我不能让1到工作,我还没有尝试过呢。

回答

7

要至少真正启动子进程,您必须告诉Popen对象真正进行通信。

def run_command(command): 
    p = subprocess.Popen(command, shell=True, 
      stdout=subprocess.PIPE, 
      stderr=subprocess.STDOUT) 
    return p.communicate() 
6

你可以看看Pexpect,模块专为基于壳程序交互设计。

例如推出scp命令并等待密码提示你:

child = pexpect.spawn('scp foo [email protected]:.') 
child.expect ('Password:') 
child.sendline (mypassword) 

为一个Python 3版本见Pexpect-u

+2

只需要补充一点,AFAICT,子流程模块真正适用于以初始输入运行然后完成的任务(如调用函数)。如果您需要持续来回(例如,用于交互式终端实用程序),那么Pexpect绝对是您的首选。 – TimStaley