Python守护程序库导入错误

时间:2017-11-20 11:57:06

标签: python daemon

我在这个脚本中遇到错误:

#!/usr/bin/env python

import sys, time, daemon

class MyDaemon(Daemon):
    def run(self):
        while True:
            time.sleep(1)

if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print("Unknown command")
            sys.exit(2)
        sys.exit(0)
    else:
        print("usage: %s start|stop|restart" % sys.argv[0])
        sys.exit(2)

它会产生以下错误:

Traceback (most recent call last):
  File "dtest2.py", line 5, in <module>
    class MyDaemon(Daemon):
NameError: name 'Daemon' is not defined

我做错了什么?我已经用'sudo pip install daemon'安装了守护进程。

更新:根据@DeepSpace的建议,我已将代码更改为:

#!/usr/bin/env python

import sys, time, daemon

class MyDaemon(daemon.Daemon):
    def run(self):
        while True:
            time.sleep(1)

if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print("Unknown command")
            sys.exit(2)
        sys.exit(0)
    else:
        print("usage: %s start|stop|restart" % sys.argv[0])
        sys.exit(2)

...它会产生不同的错误

Traceback (most recent call last):
  File "dtest.py", line 3, in <module>
    import sys, time, daemon
  File "/usr/local/lib/python3.6/site-packages/daemon.py", line 70
    os.umask(022)   # Don't allow others to write
               ^
SyntaxError: invalid token

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

import sys, time, daemon没有告诉口译员Daemon班来自何处。

class MyDaemon(Daemon)更改为class MyDaemon(daemon.Daemon)

更改

import sys, time, daemon

import sys
import time
from daemon import Daemon

根据PEP8 each import should be on its own line anyway