简体   繁体   English

如何检查 Python 脚本是否已经在运行

[英]How to check if Python script is already running

I have python script on Ubuntu, which sometimes running more than 24 hours.我在 Ubuntu 上有 python 脚本,有时运行超过 24 小时。 I have set in cron, to run this script every day.我已经设置了 cron,每天运行这个脚本。 However if script is still running, I would like to terminate new instance of this script.但是,如果脚本仍在运行,我想终止此脚本的新实例。 I have already found some solution, but they seems to be complicated.我已经找到了一些解决方案,但它们似乎很复杂。 I would like to add few lines in the beginning of script, which will be checking if the script is running, if yes return, else continue.我想在脚本的开头添加几行,这将检查脚本是否正在运行,如果是则返回,否则继续。

I like this command:我喜欢这个命令:

pgrep -a python | grep 'script.py'

it is possible to make some smart solution for this problem?有可能为这个问题做出一些聪明的解决方案吗?

There is no simple way how to do it.没有简单的方法可以做到这一点。 As mentioned in comments you can use creation of some locking file.如评论中所述,您可以使用创建一些锁定文件。 But i prefer use of sockets.但我更喜欢使用 sockets。 Not sure if it works same on Linux but on Windows i use this:不确定它在 Linux 上是否同样有效,但在 Windows 上我使用这个:

import socket

class AppMutex:
    """
    Class serves as single instance mutex handler (My application can be run only once).
    It use OS default property where single UDP port can be bind only once at time.
    """

    @staticmethod
    def enable():
        """
        By calling this you bind UDP connection on specified port.
        If binding fails then port is already opened from somewhere else.
        """

        try:
            AppMutex.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
            AppMutex.sock.bind(("127.0.0.1", 40000))
        except OSError:
            raise Exception("Application can be run only once.")

Simple call at begining of your script:脚本开头的简单调用:

AppMutex.enable()

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

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