I get error with this script:
#!/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)
It yields the following error:
Traceback (most recent call last):
File "dtest2.py", line 5, in <module>
class MyDaemon(Daemon):
NameError: name 'Daemon' is not defined
What am I doing wrong? I have installed daemon with 'sudo pip install daemon'.
UPDATE: following the advice from @DeepSpace I have changed the code to:
#!/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)
...and it yields a different error
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
Any suggestions?
import sys, time, daemon
does not tell the interpreter where does the Daemon
class come from.
Either change class MyDaemon(Daemon)
to class MyDaemon(daemon.Daemon)
,
or change
import sys, time, daemon
to
import sys
import time
from daemon import Daemon
According to PEP8 each import
should be on its own line anyway .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.