Python contextmanager记录失败

Python contextmanager记录失败,python,python-2.7,contextmanager,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')

我试图编写一个锁函数,使脚本在同一时间只运行一个实例。但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
回溯(最近一次呼叫最后一次):
文件“/home/vagrant/.pycharm\u helpers/pydev/pydevd.py”,第1733行,在
运行(安装程序['file'],无,无)
文件“/home/vagrant/.pycharm\u helpers/pydev/pydevd.py”,第1226行,运行中
pydev_imports.execfile(文件、全局、局部)#执行脚本
文件“/vagrant/my_script”,第274行,在
使用lockfile():
文件“/usr/lib/python2.7/contextlib.py”,第17行,输入__
返回self.gen.next()
文件“/vagrant/my_script”,第56行,锁文件
logging.INFO('找到带pid的锁文件')
TypeError:“int”对象不可调用

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

您可能希望使用


logging.INFO
是一个常量(),你的意思是。Python区分大小写。
...
logging.info('Removing stale lock file')

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