contextmanager因日志记录而失败

时间:2014-11-10 16:00:57

标签: python python-2.7 contextmanager

我尝试编写一个锁定函数,只能同时运行一个脚本实例。但是当我在我的代码中添加调试消息或其他函数时,contextmanager不喜欢它。

如何使用相同的功能和日志消息解决此问题?

锁定功能:

@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)

通话功能

with lockfile():
    do something

回溯:

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

1 个答案:

答案 0 :(得分:1)

logging.INFO不是一个功能。它是一个int对象,表示不可调用的日志记录级别。

您可能希望改为使用logging.info

...
logging.info('Removing stale lock file')

...
logging.info('Process still running. Aborting')