键盘中断后获取子进程的输出

时间:2018-07-23 17:42:15

标签: python subprocess

我想在用户执行键盘中断后将子过程的最后输出存储到变量中。我的问题主要是无尾的子流程,即下面的示例中的tail。这是我的代码:

class Testclass:
    def Testdef(self):
        try:
            global out
            print "Tail running"
            tail_cmd='tail -f log.Reconnaissance'
            proc = subprocess.Popen([tail_cmd], stdout=subprocess.PIPE, shell=True)
            (out, err) = proc.communicate()
        except KeyboardInterrupt:
            print("KeyboardInterrupt received, stopping…")
        finally:
            print "program output:", out

if __name__ == "__main__":
    app = Testclass()
    app.Testdef()

下面是它的输出,目前我还不了解。

Tail running
program output:
Traceback (most recent call last):
  File "./2Test.py", line 19, in <module>
    app.Testdef()
  File "./2Test.py", line 15, in Testdef
    print "program output:", out
NameError: global name 'out' is not defined

1 个答案:

答案 0 :(得分:0)

out未定义表示进程proc.communicate()未返回任何值,否则它将填充您的元组(out, err)。现在,找出是否应该返回communicate()方法,或者更有可能键盘中断只是杀死了它,从而阻止了out的定义。


我假设您已导入subprocess模块,但请确保先进行此操作。我改写了您的程序,而没有使用global outtry语句。

import subprocess
class Testclass:
    def __init__(self,out):    # allows you to pass in the value of out
        self.out = out    # makes out a member of this class
    def Testdef(self):
        print("Tail running")
        tail_cmd='tail -f log.Reconnaissance'
        proc = subprocess.Popen([tail_cmd], stdout=subprocess.PIPE, shell=True)
        # Perhaps this is where you want to implement the try:
        (self.out, err) = proc.communicate()
        # and here the except:
        # and here the finally:

if __name__ == "__main__":
    app = Testclass(1)    # pass 1 (or anything for testing) to the out variable
    app.Testdef()
    print('%r' % app.out) # print the contents of the out variable
                          # i get an empty string, ''

该程序按原样运行一次。 out中没有任何内容。我相信要创建一个有意义的用户中断键盘示例,我们需要程序执行可以中断的操作。也许将来我可以提供一个示例...