Durga Swaroop
Durga Swaroop

Reputation: 583

How to run a python process in the background continuosly

I'm trying to build a todo manager in python where I want to continuously run a process in the bg that will alert the user with a popup when the specified time comes. I'm wondering how I can achieve that. I've looked at some of the answers on StackOverflow and on other sites but none of them really helped. So, What I want to achieve is to start a bg process once the user enters a task and keep on running it in the background until the time comes. At the same time there might be other threads running for other tasks as well that will end at their end times.

So far, I've tried this:

t = Thread(target=bg_runner, kwargs={'task': task, 'lock_file': lock_file_path})
t.setName("Get Done " + task.
t.start()
t.join()

With this the thread is continuosly running but it runs in the foreground and only exits when the execution is done.

If I add t.daemon = True in the above code, the main thread immediately exits after start() and it looks like the daemon is also getting killed then.

Please let me know how this can be solved.

Upvotes: 2

Views: 2513

Answers (2)

user3657941
user3657941

Reputation:

The first thing you need to do is prevent your script from exiting by adding a while loop in the main thread:

import time
from threading import Thread

t = Thread(target=bg_runner, kwargs={'task': task, 'lock_file': lock_file_path})
t.setName("Get Done " + task)
t.start()
t.join()
while True:
    time.sleep(1.0)

Then you need to put it in the background:

$ nohup python alert_popup.py >> /dev/null 2>&1 &

You can get more information on controlling a background process at this answer.

Upvotes: 1

JJK
JJK

Reputation: 848

I'm guessing that you just don't want to see the terminal window after you launch the script. In this case, it is a matter of how you execute the script.

Try these things.

If you are using a windows computer you can try using pythonw.exe:

pythonw.exe example_script.py

If you are using linux (maybe OSx) you may want to use 'nohup' in the terminal.

nohup python example_script.py


More or less the reason you have to do this comes down to how the Operating system handles processes. I am not an expert on this subject matter, but generally if you launch a script from a terminal, that script becomes a child process of the terminal. So if you exit that terminal, it will also terminate any child processes. The only way to get around that is to either detach the process from the terminal with something like nohup.

Now if you end up adding the #!/usr/bin/env python shebang line, your os could possibly just run the script without a terminal window if you just double click the script. YMMV (Again depends on how your OS works)

Upvotes: 1

Related Questions