当前位置 : 主页 > 网络推广 > seo >

如何检索python中的进程开始时间(或正常运行时间)

来源:互联网 收集:自由互联 发布时间:2021-06-16
如何在Linux中检索python中的进程启动时间(或正常运行时间)? 我只知道,我可以调用“ps -p my_process_id -f”然后解析输出。但它不是很酷。 如果你是从python程序内部尝试测量,你可以这样
如何在Linux中检索python中的进程启动时间(或正常运行时间)?

我只知道,我可以调用“ps -p my_process_id -f”然后解析输出。但它不是很酷。

如果你是从python程序内部尝试测量,你可以这样做:

import time
# at the beginning of the script
startTime = time.time()
# ...
def getUptime():
    """
    Returns the number of seconds since the program started.
    """
    # do return startTime if you just want the process start time
    return time.time() - startTime

否则,你别无选择,只能解析ps或进入/ proc / pid。一个漂亮的bashy方式获得经过的时间是:

ps -eo pid,etime | grep $YOUR_PID | awk '{print $2}'

这将只打印以下格式的已用时间,因此应该很容易解析:

days-HH:MM:SS

(如果它运行了不到一天,它只是HH:MM:SS)

开始时间可以这样:

ps -eo pid,stime | grep $YOUR_PID | awk '{print $2}'

不幸的是,如果你的进程今天没有开始,这只会给你开始的日期,而不是时间。

这样做的最好的方法是获得经过的时间和当前时间,只是做一点数学。以下是一个python脚本,它使用PID作为参数,并为您执行上述操作,打印出进程的开始日期和时间:

import sys
import datetime
import time
import subprocess

# call like this: python startTime.py $PID

pid = sys.argv[1]
proc = subprocess.Popen(['ps','-eo','pid,etime'], stdout=subprocess.PIPE)
# get data from stdout
proc.wait()
results = proc.stdout.readlines()
# parse data (should only be one)
for result in results:
    try:
        result.strip()
        if result.split()[0] == pid:
            pidInfo = result.split()[1]
            # stop after the first one we find
            break
    except IndexError:
        pass # ignore it
else:
    # didn't find one
    print "Process PID", pid, "doesn't seem to exist!"
    sys.exit(0)
pidInfo = [result.split()[1] for result in results
           if result.split()[0] == pid][0]
pidInfo = pidInfo.partition("-")
if pidInfo[1] == '-':
    # there is a day
    days = int(pidInfo[0])
    rest = pidInfo[2].split(":")
    hours = int(rest[0])
    minutes = int(rest[1])
    seconds = int(rest[2])
else:
    days = 0
    rest = pidInfo[0].split(":")
    if len(rest) == 3:
        hours = int(rest[0])
        minutes = int(rest[1])
        seconds = int(rest[2])
    elif len(rest) == 2:
        hours = 0
        minutes = int(rest[0])
        seconds = int(rest[1])
    else:
        hours = 0
        minutes = 0
        seconds = int(rest[0])

# get the start time
secondsSinceStart = days*24*3600 + hours*3600 + minutes*60 + seconds
# unix time (in seconds) of start
startTime = time.time() - secondsSinceStart
# final result
print "Process started on",
print datetime.datetime.fromtimestamp(startTime).strftime("%a %b %d at %I:%M:%S %p")
网友评论