0
我正在爲單個實例設置cron作業。 下面的鎖是否需要全局?我相信是這樣,以便它保持在範圍內直到程序結束。或者至少在try/except塊之外。另外,Python的返回值應該是正值?似乎-2 echo 254上返回?在bash中。使用flock時鎖定文件是否需要全局
import time, fcntl, sys
LOCK_FILE = '/tmp/test_flock.lock'
lock = None
def do_wait():
print ('waiting N sec')
time.sleep(3)
def main(argv=None):
try:
global lock
lock = open(LOCK_FILE,'w')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
print ("got flock")
except IOError as err:
print ("Could not obtain lock file")
return -2
if argv is None:
argv = sys.argv
try:
print ('entering main')
print ('waiting')
# raise ValueError("Error raised")
do_wait()
print ('done')
except Exception as err:
print ("Exception in main")
return -1
if __name__ == '__main__':
sys.exit(main())