【问题标题】:Write log-file on sigterm in a process terminated with p.terminate()在以 p.terminate() 终止的进程中在 sigterm 上写入日志文件
【发布时间】:2017-04-02 06:19:47
【问题描述】:

我用p.terminate 终止我的子进程,我是这样打开的:

p = Popen([sys.executable, args], stdin=PIPE, stdout=PIPE, stderr=open("error.txt", 'a'))

如您所见,我将所有错误重定向到一个文本文件,以便我可以轻松阅读它。 当子进程终止时,我误用了此功能将某些内容打印到此文件中:

signal.signal(signal.SIGTERM, sigterm_handler) # sets shutdown_flag
while True:
    if shutdown_flag:
        print("Some Useful information", file=sys.stderr)

但是:文件始终为空。这是因为当调用terminate 时管道关闭并且此时从子进程写入的任何内容都丢失了?或者还有其他我在这里没有看到的问题?

【问题讨论】:

    标签: python subprocess sigterm


    【解决方案1】:

    一般来说,终止线程不是一个好主意。相反,您应该使用 threading.Event 要求它结束。

    event = threading.Event() 
    while not event.isSet():   # use this instead of while True:
        #  do your stuff
    
    # now write your file
    print("Some Useful information", file=sys.stderr)
    

    然后,代替 p.terminate(),使用:

    threading.Event().set()
    

    【讨论】:

    • 我使用的不是线程而是子进程。它仍然以同样的方式工作吗?
    • 我的错。我脑子里有线。你能做的也是类似的。也就是说,告诉进程退出而不是杀死它。我建议使用 p.communicate("please shut down") 代替 p.terminate() 然后,而不是在我原来的 sn-p 中等待事件,我们在 stdin 上的数据并寻找“请关闭”(或任何你想要的字符串)。另外,重要的是,在 p.communicate() 之后,执行 p.wait()。
    • 这在我的情况下不容易完成,因为我将数据传输到进程。设置您的解决方案会混淆数据流和控制流,我想保持分开
    猜你喜欢
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2018-06-06
    • 2023-02-25
    相关资源
    最近更新 更多