Reputation: 659
I tried to write a lock functionto have only one instance of my script running at the same time. But contextmanager doesn't like it when I add debug messages or other functions into my code.
Any ideas how to workaround this with the same functionality and log messages?
Lock function:
@contextmanager
def lockfile(lock_file='/run/lock/my_script.lock'):
if os.path.exists(lock_file):
logging.INFO('Found lock file with pid')
lf = open(lock_file)
pid = lf.readline()
try:
os.kill(pid, 0)
except OSError:
logging.INFO('Removing stale lock file')
os.remove(lock_file)
else:
logging.INFO('Process still running. Aborting')
sys.exit(1)
if not os.path.exists(lock_file):
pid = os.getpid()
open(lock_file, 'w').write(pid)
try:
yield
finally:
os.remove(lock_file)
call function
with lockfile():
do something
Traceback:
Traceback (most recent call last):
File "/home/vagrant/.pycharm_helpers/pydev/pydevd.py", line 1733, in <module>
debugger.run(setup['file'], None, None)
File "/home/vagrant/.pycharm_helpers/pydev/pydevd.py", line 1226, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/vagrant/my_script", line 274, in <module>
with lockfile():
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/vagrant/my_script", line 56, in lockfile
logging.INFO('Found lock file with pid')
TypeError: 'int' object is not callable
Upvotes: 0
Views: 365
Reputation: 369054
logging.INFO
is not a function. It's an int object that represent logging level which is not callable.
You may want to use logging.info
instead.
...
logging.info('Removing stale lock file')
...
logging.info('Process still running. Aborting')
Upvotes: 1