我正在使用 python-daemon 模块来管理我的 Python 脚本的守护进程。 但是,在运行我根本无法弄清楚的脚本时,我感到很头疼。我也不知道如何开始调试它。
我有代码:
def run_application():
#Do something here...
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = 'stdout.txt'
self.stderr_path = 'stdlog.log'
self.pidfile_path = 'filelock.pid'
self.pidfile_timeout = 5
def run(self):
run_application()
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
运行时,它总是将以下内容写入stdlog.log:
Traceback (most recent call last):
File "MyApp.py", line 335, in <module>
daemon_runner.do_action()
File "/anaconda/lib/python2.7/site-packages/daemon/runner.py", line 189, in do_action
func(self)
File "/anaconda/lib/python2.7/site-packages/daemon/runner.py", line 124, in _start
self.daemon_context.open()
File "/anaconda/lib/python2.7/site-packages/daemon/daemon.py", line 346, in open
self.pidfile.__enter__()
File "/anaconda/lib/python2.7/site-packages/lockfile/__init__.py", line 229, in __enter__
self.acquire()
File "/anaconda/lib/python2.7/site-packages/daemon/pidfile.py", line 42, in acquire
super(TimeoutPIDLockFile, self).acquire(timeout, *args, **kwargs)
File "/anaconda/lib/python2.7/site-packages/lockfile/pidlockfile.py", line 88, in acquire
self.path)
lockfile.LockTimeout: Timeout waiting to acquire lock for /MyApp/filelock.pid
因此在尝试锁定 filelock.pid 时似乎超时。我不知道这是为什么。我已经删除了 filelock.pid,我已经更改了权限;每次都出现同样的错误。
我怎样才能开始调试这个???我很茫然。
我正在使用 python-daemon version 1.6(如果重要的话)。
更新:
遵循建议here ,我现在看到已经有一个进程在运行。现在我怎样才能弄清楚如何确定正在运行的守护进程的 PID。
请您参考如下方法:
我同意@ExploWare 就他如何证明您可以捕获那些LockTimeout 异常而言。
至于调试和查看哪个进程持有此锁的方法,这里是您可以运行的外部代码位...
import daemon.pidfile
import os
import lockfile
# We know the lockfile name.
pidfile = daemon.pidfile.PIDLockFile(
os.path.join("/MyApp/","filelock.pid"))
# This current process id...
os.getpid()
# 46337
那么是什么进程获得了这个锁呢?
pidfile.is_locked()
# True
pidfile.read_pid()
# 96856
当我们的 PIDLockFile 实例尝试“获取”时,
pidfile.__dict__
# {'unique_name': '/MyApp/filelock.pid', 'lock_file': '/MyApp/filelock.pid.lock', 'hostname':
# 'MyMachine.local', 'pid': 46337, 'timeout': None, 'tname': '', 'path': '/MyApp/filelock.pid'}
pidfile.acquire()
#
# (Had to Control-C quit because I didnt set a timeout on PIDLockFile )
#
# ^CTraceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/Users/michal/venf/lib/python2.7/site-packages/lockfile/pidlockfile.py", line 92, in acquire
# time.sleep(timeout is not None and timeout/10 or 0.1)
# KeyboardInterrupt
因此,改为使用@ExploWare 的异常捕获。
# Wait only 5 seconds.
pidfile.timeout = 5
try:
pidfile.acquire()
except lockfile.LockTimeout:
print 'locked . need to wait or move on.'
#
# locked . need to wait or move on.
