简体   繁体   中英

Check if python script running from another python script linux

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM