2013-02-10 101 views
1

我需要启动进程并在进程运行时读取该进程的输出。我希望能够打印输出(可选)并在处理完成时返回输出。以下是我迄今为止(从其他答案在计算器合并​​):在进程运行时读取进程的输出

def call(command, print_output): 
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    out = "" 

    while True: 
     line = process.stdout.readline().rstrip().decode("utf-8") 
     if line == '': 
      break 

     if print_output: 
      print(line) 

     out += line + "\n" 

    process.wait() 

    return process.returncode, out 

这段代码在窗口(与Windows 7,蟒蛇3.3测试)的伟大工程,但在Linux失败(Ubuntu的12.04,蟒蛇3.2)。在linux中,脚本挂在线上

line = process.stdout.readline().rstrip().decode("utf-8") 

当过程结束时。

代码有什么问题?我试着检查process.poll()是否已经完成,但是在Linux下它总是返回None。

+0

在我的Linux上运行良好,3.2,并没有关闭封闭的FD似乎是一个非常不可能的错误。当你对Python程序进行分离时,你会看到什么?另外,你可以包含你使用的'command'的值吗? – phihag 2013-02-10 20:33:11

+1

感谢您的评论!问题实际上是命令,它是一个“svn export ...”,svn进程第一次需要用户输入(login,passwort)。对不起,... – osiris81 2013-02-10 23:20:46

回答

0

文档说

Warning Use communicate() rather than 
.stdin.write, .stdout.read or .stderr.read to 
avoid deadlocks due to any of the other OS pipe buffers filling 
up and blocking the child process. 

我知道我以前对Windows中的问题。

我假设命令以某种方式在非缓冲模式下运行。

该文档有使用子过程的食谱你的听起来像shell-backquote但你使用subprocess是不同的。

相关问题