如何获得cmdline为["python"]且没有路径的python进程的脚本路径? [英] How to get the script path of a python process who's cmdline is ["python"], with no path?

查看:358
本文介绍了如何获得cmdline为["python"]且没有路径的python进程的脚本路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取并杀死同一脚本的所有其他正在运行的python实例,我发现一个极端的情况,其中路径不在 psutil psutil c1> 列表,当该过程以./myscript.py而不是python ./myscript.py

I'm trying to get and kill all other running python instances of the same script, I found an edge case where the path is not in psutil's cmdline list, when the process is started with ./myscript.py and not python ./myscript.py

脚本的内容是,请注意shebang:

the script's content is, note the shebang:

#!/bin/python
import os
import psutil
import sys
import time

for proc in psutil.process_iter():
    if "python" in proc.name():
        print("name", proc.name())
        script_path = sys.argv[0]
        proc_script_path = sys.argv[0]
        if len(proc.cmdline()) > 1:
            proc_script_path = proc.cmdline()[1]
        else: 
            print("there's no path in cmdline")
        if script_path.startswith("." + os.sep) or script_path.startswith(".." + os.sep):
            script_path = os.path.normpath(os.path.join(os.getcwd(), script_path))
        if proc_script_path.startswith("." + os.sep) or proc_script_path.startswith(".." + os.sep):
            proc_script_path = os.path.normpath(os.path.join(proc.cwd(), proc_script_path))
        print("script_path", script_path)
        print("proc_script_path", proc_script_path)
        print("my pid", os.getpid())
        print("other pid", proc.pid)
        if  script_path == proc_script_path and os.getpid() != proc.pid:
            print("terminating instance ", proc.pid)
            proc.kill()

time.sleep(300)

当不在 psutil 中时,如何获取python进程的脚本路径的 cmdline ?

推荐答案

调用这样的python脚本时,检查if 'python' in proc.name()是问题所在.该脚本不会显示python或python3,但会显示脚本名称.请尝试以下操作:

When invoking a python script like this, the check if 'python' in proc.name() is the problem. This will not show python or python3 for the scripts in question, but it will show the script name. Try the following:

import psutil

for proc in proc.process_iter():
    print('Script name: {}, cmdline: {}'.format(proc.name(), proc.cmdline()))

您应该看到类似()的内容: Script name: myscript.py, cmdline: ['/usr/bin/python3', './myscript.py']

You should see something like (): Script name: myscript.py, cmdline: ['/usr/bin/python3', './myscript.py']

希望这会有所帮助.

这篇关于如何获得cmdline为["python"]且没有路径的python进程的脚本路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆