Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Python Daemon

Tags:

python

daemon

I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case?

I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off about that.

like image 867
Kyle Hotchkiss Avatar asked Jan 09 '11 02:01

Kyle Hotchkiss


People also ask

What is Python daemon?

daemon-This property that is set on a python thread object makes a thread daemonic. A daemon thread does not block the main thread from exiting and continues to run in the background. In the below example, the print statements from the daemon thread will not printed to the console as the main thread exits.

How do I run a daemon process in python?

Daemon processes in Python To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.

What is the function that can help to start a background daemon process in python?

This can be achieved by creating a new multiprocessing. Process instance and setting the “daemon” argument to True. We can update the previous example to create a daemon process to execute our task() function. The task() function will then report whether it is being executed by a daemon process or not.


1 Answers

Rather than writing your own daemon, use python-daemon instead! python-daemon implements the well-behaved daemon specification of PEP 3143, "Standard daemon process library".

I have included example code based on the accepted answer to this question, and even though the code looks almost identical, it has an important fundamental difference. Without python-daemon you would have to use & to put your process in the background and nohup and to keep your process from getting killed when you exit your shell. Instead this will automatically detach from your terminal when you run the program.

For example:

import daemon import time  def do_something():     while True:         with open("/tmp/current_time.txt", "w") as f:             f.write("The time is now " + time.ctime())         time.sleep(5)  def run():     with daemon.DaemonContext():         do_something()  if __name__ == "__main__":     run() 

To actually run it:

python background_test.py 

And note the absence of & here.

Also, this other stackoverflow answer explains in detail the many benefits of using python-daemon.

like image 151
aculich Avatar answered Sep 19 '22 20:09

aculich