如果您正在尝试测量的python程序中执行此 *** 作,则可以执行以下 *** 作:
import time# at the beginning of the scriptstartTime = 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。
bash获取经过时间的一种不错的方法是:
ps -eo pid,etime | grep $YOUR_PID | awk '{print }'
这只会以以下格式打印经过的时间,因此它应该很容易解析:
days-HH:MM:SS
(如果运行了不到一天,那就只是
HH:MM:SS)
开始时间如下所示:
ps -eo pid,stime | grep $YOUR_PID | awk '{print }'
不幸的是,如果您的过程不是 今天 开始的,那么只会给您开始的日期,而不是时间。
最好的方法是获取经过时间和当前时间,然后进行一些数学运算。以下是一个Python脚本,该脚本将PID作为参数,并为您执行上述 *** 作,并打印出该过程的开始日期和时间:
import sysimport datetimeimport timeimport subprocess# call like this: python startTime.py $PIDpid = sys.argv[1]proc = subprocess.Popen(['ps','-eo','pid,etime'], stdout=subprocess.PIPE)# get data from stdoutproc.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 itelse: # didn't find one print "Process PID", pid, "doesn't seem to exist!" sys.exit(0)pidInfo = [result.split()[1] for result in resultsif 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 timesecondsSinceStart = days*24*3600 + hours*3600 + minutes*60 + seconds# unix time (in seconds) of startstartTime = time.time() - secondsSinceStart# final resultprint "Process started on",print datetime.datetime.fromtimestamp(startTime).strftime("%a %b %d at %I:%M:%S %p")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)