防止运行python脚本的并发实例

tpo*_*eux 7 python cron fcntl

可能重复:
Python:单个程序实例

我需要阻止cron作业在作业需要更长时间才能完成而不是启动器间隔时运行并发实例.我正在尝试使用flock概念来实现这一点,但fcntl模块的行为并不像我期望的那样.

任何人都可以告诉我为什么这可以防止两个并发实例:

import sys
import time
import fcntl

file_path = '/var/lock/test.py'
file_handle = open(file_path, 'w')

try:
    fcntl.lockf(file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
    print 'no other instance is running'
    for i in range(5):
        time.sleep(1)
        print i + 1

except IOError:
    print 'another instance is running exiting now'
    sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用:

import sys
import time
import fcntl

def file_is_locked(file_path):
    file_handle = open(file_path, 'w')
    try:
        fcntl.lockf(file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
        return False
    except IOError:
        return True

file_path = '/var/lock/test.py'

if file_is_locked(file_path):
    print 'another instance is running exiting now'
    sys.exit(0)
else:
    print 'no other instance is running'
    for i in range(5):
        time.sleep(1)
        print i + 1
Run Code Online (Sandbox Code Playgroud)

Bor*_*jaX 7

我的拙见(虽然我可能完全错了)是file_handle函数的本地函数(在第二种情况下),因此,一旦函数完成就会被破坏.

以下代码似乎按预期工作:

#!/usr/bin/env python
#http://stackoverflow.com/questions/14406562/prevent-running-concurrent-instances-of-a-python-script

import sys
import time
import fcntl

file_handle = None

def file_is_locked(file_path):
    global file_handle 
    file_handle= open(file_path, 'w')
    try:
        fcntl.lockf(file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
        return False
    except IOError:
        return True

file_path = '/var/lock/test.py'

if file_is_locked(file_path):
    print 'another instance is running exiting now'
    sys.exit(0)
else:
    print 'no other instance is running'
    for i in range(5):
        time.sleep(1)
        print i + 1
Run Code Online (Sandbox Code Playgroud)

请注意,我唯一做的是设置file_handle为全局变量(尽管我复制了整个代码以获得一个工作示例)