简体   繁体   English

检查特定的 Python 脚本是否已经在运行

[英]Check if a particular Python script is already running

How can I check, from a Python script, if another specific Python script is running?如何从 Python 脚本检查另一个特定的 Python 脚本是否正在运行?

def running():
    for q in psutil.process_iter():
        print q
        if q.name() == 'server_class.py':
            return True
    return False

I have tried that but the program is called "python" and not the name of the script.我已经尝试过,但该程序被称为“python”而不是脚本的名称。

The python script file will be part of the command line. python 脚本文件将成为命令行的一部分。 You can try something along these lines:您可以尝试以下方法:

def running():

    for q in psutil.process_iter():
        if q.name() == 'python':
            print q.cmdline()
            if len(q.cmdline())>1 and 'server_class.py' in q.cmdline()[1]:
                return True

    return False

I am using in just for the example.我使用in仅用于示例。 You might want to match the full path.您可能想要匹配完整路径。

Case: When you want to exit the script, if a previous instance is already running:案例:当您想退出脚本时,如果前一个实例已经在运行:

def already_running(script_name):
num_instance = 0
for q in psutil.process_iter():
    if 'python' in q.name():
        if len(q.cmdline()) > 1 and script_name in q.cmdline()[1]:
            num_instance += 1
return num_instance > 1

What it does:它能做什么:

  1. It checks for the number of instances of the script_name currently running.它检查当前运行的script_name的实例数。 If you are calling this from file xyz.py and sending xyz.py as argument, remember the current instance will also be counted如果您从文件xyz.py调用它并将xyz.py作为参数发送,请记住当前实例也将被计算在内

  2. If num_instance > 1, you have a previous instance running.如果num_instance > 1,则您有一个先前的实例正在运行。

Hope this is useful.希望这是有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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