首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >键盘中断后获取子进程的输出

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

Stack Overflow用户
提问于 2018-07-24 01:42:15
回答 1查看 134关注 0票数 0

我想在用户执行键盘中断后将子进程的最后一次输出存储到一个变量中。我的问题主要是没有结尾的子流程,也就是下面例子中的尾部。下面是我的代码:

代码语言:javascript
复制
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()

下面是它的输出,我现在还不明白。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2018-07-24 01:48:39

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

我假设您导入了subprocess模块,但请确保您首先导入了该模块。我在没有使用global outtry语句的情况下重写了程序。

代码语言:javascript
复制
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中没有任何内容。我相信要创建一个有意义的用户中断键盘的例子,我们需要程序做一些可以被中断的事情。也许我可以在未来提供一个例子。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51484491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档