39

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

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

4

6 回答 6

74

通过使用 psutil https://github.com/giampaolo/psutil

>>> import psutil, os, time
>>> p = psutil.Process(os.getpid())
>>> p.create_time()
1293678383.0799999
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(p.create_time()))
'2010-12-30 04:06:23'
>>>

...加上它是跨平台的,而不仅仅是 Linux。

注意:我是这个项目的作者之一。

于 2010-12-30T03:09:26.553 回答
24

如果您是在您尝试测量的 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. 获取经过时间的一种不错的bash方法是:

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")
于 2010-04-08T07:23:35.863 回答
15

man proc说第 22 项/proc/my_process_id/stat是:

starttime %lu

系统启动后进程开始的时间。

您现在的问题是,如何确定 jiffy 的长度以及如何确定系统何时启动。

后者的答案仍然来自man proc:它在/proc/stat,在它自己的一行上,如下所示:

btime 1270710844

这是自 Epoch 以来以秒为单位的测量值。


前者的答案我不确定。man 7 time说:

软件时钟、HZ 和 Jiffies

许多系统调用和时间戳的准确性受到软件时钟分辨率的限制,该时钟由内核维护,以 jiffies 为单位测量时间。jiffy 的大小由内核常量的值决定HZ的值HZ因内核版本和硬件平台而异。在 x86 上,情况如下:在 2.4.x 及之前的内核上,HZ为 100,给出的 jiffy 值为 0.01 秒;从 2.6.0 开始,HZ提高到 1000,一瞬间 0.001 秒;从内核 2.6.13 开始,该HZ值是内核配置参数,可以是 100、250(默认值)或 1000,产生的 jiffies 值分别为 0.01、0.004 或 0.001 秒。

我们需要 find HZ,但我不知道如何从 Python 中解决这个问题,除了希望该值为 250 (因为 Wikipedia 声称是默认值)。

ps这样得到它:

  /* sysinfo.c init_libproc() */
  if(linux_version_code > LINUX_VERSION(2, 4, 0)){ 
    Hertz = find_elf_note(AT_CLKTCK);
    //error handling
  }
  old_Hertz_hack(); //ugh

这听起来像是一个非常小的 Python C 模块完成的工作:)

于 2010-04-08T07:43:07.577 回答
6

这是基于 badp 答案的代码:

import os
from time import time

HZ = os.sysconf(os.sysconf_names['SC_CLK_TCK'])

def proc_age_secs():
    system_stats = open('/proc/stat').readlines()
    process_stats = open('/proc/self/stat').read().split()
    for line in system_stats:
        if line.startswith('btime'):
            boot_timestamp = int(line.split()[1])
    age_from_boot_jiffies = int(process_stats[21])
    age_from_boot_timestamp = age_from_boot_jiffies / HZ
    age_timestamp = boot_timestamp + age_from_boot_timestamp
    return time() - age_timestamp

我不确定它是否正确。我编写了一个调用 sleep(5) 的测试程序,然后运行它,输出是错误的,并且每次运行都会在几秒钟内发生变化。这是在 vmware 工作站 vm 中:

if __name__ == '__main__':
    from time import sleep
    sleep(5)
    print proc_age_secs()

输出是:

$ time python test.py
6.19169998169

real    0m5.063s
user    0m0.020s
sys     0m0.036s
于 2011-12-23T14:46:57.053 回答
3
def proc_starttime(pid=os.getpid()):
    # https://gist.github.com/westhood/1073585
    p = re.compile(r"^btime (\d+)$", re.MULTILINE)
    with open("/proc/stat") as f:
        m = p.search(f.read())
    btime = int(m.groups()[0])

    clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
    with open("/proc/%d/stat" % pid) as f:
        stime = int(f.read().split()[21]) / clk_tck

    return datetime.fromtimestamp(btime + stime)
于 2015-07-28T13:00:42.280 回答
1

你可以解析/proc/uptime

>>> uptime, idletime = [float(f) for f in open("/proc/uptime").read().split()]
>>> print uptime
29708.1
>>> print idletime
26484.45

对于 Windows 机器,您可能可以使用wmi

import wmi
c = wmi.WMI()
secs_up = int([uptime.SystemUpTime for uptime in c.Win32_PerfFormattedData_PerfOS_System()][0])
hours_up = secs_up / 3600
print hours_up
于 2010-04-08T07:41:11.387 回答