0

I have actualy python script running on background, you can see how it's displayed when i use command "ps -aux" :

root       405  0.0  2.6  34052 25328 ?        S    09:52   0:04 python3 -u /opt/flask_server/downlink_server/downlink_manager.py

i want to check if this script are running from another python script, so i try to us psutil module, but it just detect that python3 are running but not my script precisely ! there is my python script :

import os
import psutil
import time
import logging
import sys

for process in psutil.process_iter():
if process.cmdline() == ['python3', '/opt/flask_server/downlink_server/downlink_manager.py']:
    print('Process found: exiting.')

It's look like simple, but trust me, i already try other function proposed on another topic, like this :

def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
    if name == p.info['name'] or \
            p.info['exe'] and os.path.basename(p.info['exe']) == name or \
            p.info['cmdline'] and p.info['cmdline'][0] == name:
        ls.append(p)

return ls

ls = find_procs_by_name("downlink_manager.py")

But this function didn't fin my script, it's work, when i search python3 but not the name of the script.

Of course i try to put all the path of the script but nothing, can you please hepl me ?

jayen marco
  • 103
  • 2
  • 12
  • 1
    This might help you, https://stackoverflow.com/questions/46979567/find-processes-by-command-in-python/46980830 – sushanth Jun 04 '20 at 11:05
  • Note that if the first process is *expected* to be watched, it should maintain a PID file/lock. See e.g. [What is a .pid file and what does it contain?](https://stackoverflow.com/questions/8296170/what-is-a-pid-file-and-what-does-it-contain) – MisterMiyagi Jun 04 '20 at 11:28
  • Your ``ps`` output shows ``python3 -u /opt/...``, but your Python code checks for ``process.cmdline() == ['python3', '/opt/...'`` (note the missing ``-u``). Is this intentional? – MisterMiyagi Jun 04 '20 at 11:31
  • @MisterMiyagi I try also 'python3 -u', but nothing change – jayen marco Jun 04 '20 at 12:09

1 Answers1

2

I resolve the issue with this modification :

import psutil

proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
process = any("/opt/flask_server/downlink_server/downlink_manager.py" in p.info["cmdline"] for p in proc_iter)
print(process)
jayen marco
  • 103
  • 2
  • 12