【问题标题】:Python: Amount of wall time a process has been runningPython:进程运行的时间
【发布时间】:2009-12-14 09:40:15
【问题描述】:

我想做这样的事情:

try:
    pid = int(file(lock_file, "r").read())
    print "%s exists with pid: %s" % (lock_file, pid)
    if not check_pid(pid):
        print "%s not running. Phantom lock file? Continuing anyways" % pid
    elif wall_time(pid) > 60 * 5:
        print "%s has been running for more than 5 minutes. Killing it" % pid
        os.kill(pid)
    else:
        print "Exiting"
        sys.exit()
except IOError:
    pass

lock = file(lock_file, "w")
lock.write("%s" % os.getpid())
lock.close()

如何实现wall_time?我必须阅读/proc 还是有更好的方法?

【问题讨论】:

    标签: python process


    【解决方案1】:

    也许您可以查看锁定文件的创建时间。这不能保证正确,但在大多数情况下它是正确的(而且错误的后果很小)。

    【讨论】:

    • 这有什么问题吗? elif time.time() - os.stat(lock_file).st_mtime > 60 * 5
    • 我会选择st_ctime 而不是st_mtime,否则看起来不错。
    【解决方案2】:

    如果你因为某种原因不想使用锁文件的修改时间,你可以把它写在文件里:

    pid, start_time = map(int, file(lock_file, "r").read().split())
    ...
    lock.write("%s %d" % (os.getpid(), time.time()))
    

    【讨论】:

      猜你喜欢
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 2018-10-27
      • 2015-08-20
      • 2010-12-18
      • 1970-01-01
      • 2019-11-15
      相关资源
      最近更新 更多