获取pgrep以确定pid已运行的长度

2024-04-26 13:06:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我删掉了一些代码来概述我要做的事情。我只是语法不太正确,有人能帮我吗?你知道吗

def calc_execution():
    import subprocess
    #get the proc id of detectmotion; need help converting into subprocess
    detectmotion_file_pid = subprocess.call(pgrep -f "detectmotion.py")
    if detectmotion_file_pid:
        #determine how long pid has been running; note this seems to be incorrect
        len_run_time=subprocess.call(ps -o etime= -p detectmotion_file_pid)
        print len_run_time

我的问题是如何让vardetectmotion_file_pidlen_run_time的语法正常工作。你知道吗

有人能帮忙吗?你知道吗

谢谢


Tags: run代码importlentimedef语法calc
1条回答
网友
1楼 · 发布于 2024-04-26 13:06:34

subprocess.call()需要一个字符串或字符串数组作为args参数-请参阅文档here。你知道吗

您提供:

subprocess.call(pgrep -f "detectmotion.py"),python将其解释为:

  • 取变量pgrep的值,然后减去f
  • “字符串”检测运动.py““

你真正的意思是:

subprocess.call([ 'pgrep',  '-f',  'detectmotion.py'])

该数组中的每个项都用作下一个进程的参数。pgrep标识要运行的二进制文件(并在新进程中显示为arg0)。-fdetectmotion.py是下一个参数。你知道吗

对于下一个(获取运行时),您将再次执行相同的操作 -下面是一个简单的修复。你知道吗

subprocess.call(['ps',  '-o',  'etime=',  '-p', detectmotion_file_pid ])

最后一个问题是,您希望返回值subprocess.call()就是您要查找的数据。事实上,subprocess.call()将:

Wait for command to complete, then return the returncode attribute.

如果您想捕获刚刚运行的命令的输出,那么您需要使用“管道”,将命令的输出带入您的应用程序,这就是事情变得混乱的地方,文档说:

Note: Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process output volume. You can use Popen with the communicate() method when you need pipes.

所以。。。你知道吗

x = subprocess.Popen([ 'pgrep',  '-f',  'detectmotion.py'])
out, _ = x.communicate()

# out is currently a string, e.g: '26585\n'
print(out)

# convert it into an integer:
detectmotion_file_pid = int(out.rstrip())

您需要对ps -o etime= -p ...的输出执行类似的操作,因为这将以可读的格式返回时间。你知道吗

x = subprocess.Popen(['ps',  '-o',  'etime=',  '-p', str(detectmotion_file_pid) ])
out, _ = x.communicate()

# out is currently a string, e.g: '      12:53\n'
print(out)

# strip it
out = out.strip()

# now it's free of white-space, e.g: '12:53'
print(out)

此时,您可能会问自己如何将看似mm:ss的格式转换为更有用的格式。。。不幸的是,ps的输出是为人类设计的,并且像这样解析可能不是非常简单。你知道吗

您可能更喜欢查看^{},它可以告诉您有关进程的各种信息:

相关问题 更多 >