只允许一个python脚本实例? [重复]

时间:2022-01-12 16:23:29

This question already has an answer here:

这个问题在这里已有答案:

I have a python script that I want to only allow to be running once on a machine. I want it to print something like "Error, already running" if it is already running, whether its running in the background or in a different ssh session. How would I do this? Here is my script.

我有一个python脚本,我只想允许在一台机器上运行一次。我希望它打印像“错误,已经运行”的东西,如果它已经在运行,无论是在后台运行还是在不同的ssh会话中运行。我该怎么办?这是我的剧本。

import urllib, urllib2, sys
num = sys.argv[1]
print 'Calling'
phones = [
'http://phone1/index.htm',
'http://phone2/index.htm',
'https://phone3/index.htm',
'https://phone4/index.htm',
'https://phone5/index.htm'
]
data = urllib.urlencode({"NUMBER":num, "DIAL":"Dial", "active_line":1})
while 1: 
    for phone in phones:
        try:
            urllib2.urlopen(phone,data) # make call
            urllib2.urlopen(phone+"?dialeddel=0") # clear logs
        except: pass

P.S I am using CentOS 5 if that matters.

如果重要的话,我正在使用CentOS 5。

3 个解决方案

#1


3  

  1. You can implement a lock on the file.
  2. 您可以对文件实施锁定。

  3. Create a temp file at the start of the execution and check if that file is present before running the script.
  4. 在执行开始时创建临时文件,并在运行脚本之前检查该文件是否存在。

Refer to this post for answer- Check to see if python script is running

请参阅这篇文章以获得答案 - 检查python脚本是否正在运行

#2


2  

You can install the single package with pip install single that will use an advisory lock to ensure that only a single instance of a command will run without leaving stale lock files behind.

您可以使用pip install single安装单个软件包,该软件包将使用建议锁定以确保只运行命令的单个实例而不会留下陈旧的锁定文件。

You can invoke it on your script like this:

您可以在脚本上调用它,如下所示:

single.py -c long-running-script arg1 arg2

#3


0  

You could lock an existing file using e.g. flock at start of your script. Then, if the same script is run twice, the latest started would block. See also this question.

您可以使用例如锁定现有文件在你的剧本开始时蜂拥而至。然后,如果同一个脚本运行两次,则最新启动将阻止。另见这个问题。

#1


3  

  1. You can implement a lock on the file.
  2. 您可以对文件实施锁定。

  3. Create a temp file at the start of the execution and check if that file is present before running the script.
  4. 在执行开始时创建临时文件,并在运行脚本之前检查该文件是否存在。

Refer to this post for answer- Check to see if python script is running

请参阅这篇文章以获得答案 - 检查python脚本是否正在运行

#2


2  

You can install the single package with pip install single that will use an advisory lock to ensure that only a single instance of a command will run without leaving stale lock files behind.

您可以使用pip install single安装单个软件包,该软件包将使用建议锁定以确保只运行命令的单个实例而不会留下陈旧的锁定文件。

You can invoke it on your script like this:

您可以在脚本上调用它,如下所示:

single.py -c long-running-script arg1 arg2

#3


0  

You could lock an existing file using e.g. flock at start of your script. Then, if the same script is run twice, the latest started would block. See also this question.

您可以使用例如锁定现有文件在你的剧本开始时蜂拥而至。然后,如果同一个脚本运行两次,则最新启动将阻止。另见这个问题。