如何在python中获取名称的进程ID

问题描述 投票:0回答:1

我正在尝试构建一个简单的python脚本,它现在可以完成一件事:它会在给定PID的过程中找到进程的进程ID。我在这里看了一下,发现了许多不同的资源,但没有一个非常符合我的需求。最有帮助的是this one,我用他们的例子试图取得进展。

现在我有这个:

from subprocess import check_output

def get_pid(name):
    return check_output(["pidof",name])

print(get_pid("fud"))

我正在使用sudo top在不同的终端窗口中查看我的所有进程。我在屏幕上看到一个特别命名为“fud”的进程并知道它正在运行。当我为该进程和任何其他进程运行程序时,我得到了这个:

  File "fort.py", line 6, in <module>
    print(get_pid("fud"))
  File "fort.py", line 4, in get_pid
    return check_output(["pidof",name])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我不太确定这里发生了什么,并且想要有效地纠正这个错误并做我想做的事情的详细指导。谢谢!

python command-line process subprocess pid
1个回答
0
投票

我已经找到了解决方案。这很简单:

print(commands.getoutput('pgrep FortniteClient-Mac-Shipping'))

希望有人可以使用这一天。谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.