python cmdline_如何获取cmdline为[“ python”]且没有路径的python进程的脚本路径?

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

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)

how can I get the script path of a python process when it's not in psutil's cmdline?

解决方案

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()))

You should see something like ():

Script name: myscript.py, cmdline: ['/usr/bin/python3', './myscript.py']

Hope this helps.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值