【问题标题】:Detect hanging python shell in OS X在 OS X 中检测挂起的 python shell
【发布时间】:2014-02-06 17:32:55
【问题描述】:

我有一个程序实现了一个错误的库,由于不正确地实现并行化,该库偶尔会挂起。

我没有时间解决核心问题,所以我正在寻找一个技巧来确定进程何时挂起而不是正常工作。

是否有任何 OS X 或 python 特定的 API 来执行此操作?是否可以使用另一个线程甚至主线程重复解析stdout,以便当最后几行在一定时间内没有改变时,通知另一个线程并可以杀死行为不端的线程? (然后重启?

【问题讨论】:

    标签: python multithreading macos terminal stdout


    【解决方案1】:

    基本上你正在寻找一个监控进程。它将运行一个命令(或一组命令)并观察它们的执行以寻找特定的东西(在你的情况下,stdout 保持沉默)。参考下面的 2 个 SO 问题(以及一些文档的简要介绍),您可以快速构建一个超级简单的监视器。

    https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line https://stackoverflow.com/questions/3471461/raw-input-and-timeout

    # monitor.py
    import subprocess
    
    TIMEOUT = 10
    while True:
      # start a new process to monitor
      # you could also run sys.argv[1:] for a more generic monitor
      child = subprocess.Popen(['python','other.py','arg'], stdout=subprocess.PIPE)
      while True:
        rlist,_,_ = select([child.stdout], [], [], TIMEOUT)
        if rlist:
          child.stdout.read() # do you need to save the output?
        else:
          # timeout occurred, did the process finish?
          if child.poll() is not None:
            # child process completed (or was killed, but didn't hang), we are done
            sys.exit()
          else:
            # otherwise, kill the child and start a new one
            child.kill()
            break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 2012-12-20
      • 1970-01-01
      相关资源
      最近更新 更多