Reputation: 285
I am trying to build a simple python script that does one thing right now: it finds the process id of a process given it's PID. I have looked on here and found many different resources, but none that quite fit what I need. The most helpful is this one and I have used their example to try to make progress.
Right now I have this:
from subprocess import check_output
def get_pid(name):
return check_output(["pidof",name])
print(get_pid("fud"))
I am using sudo top to view all my processes in a different terminal window. There is one process in particular named "fud" that I see on the screen and know that it is running. When I run the program for that process and any other process I get this:
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
I am not really sure what is going on here, and would like detailed guidance on an effective way to correct this mistake and do what I am trying to do. Thanks!
Upvotes: 1
Views: 8168
Reputation: 903
You can use psutil
package:
Install
pip install psutil
Usage: In order to get process id using process name refer the following snippet:
import psutil
process_name = "fud"
def get_pid(process_name):
for proc in psutil.process_iter():
if proc.name() == process_name:
return proc.pid
Upvotes: 1
Reputation: 285
I have since found the solution. It is very simple:
print(commands.getoutput('pgrep FortniteClient-Mac-Shipping'))
Hope someone can use this one day. Thanks.
Upvotes: 1