If you want to run any Python script in Background in Windows operating System then all you are required to do is to rename the extension of your existing Python script that you want to run in background to '. pyw'.
Run nohup python bgservice.py & to get the script to ignore the hangup signal and keep running. Output will be put in nohup. out . Ideally, you'd run your script with something like supervise so that it can be restarted if (when) it dies.
Run nohup python bgservice.py &
to get the script to ignore the hangup signal and keep running. Output will be put in nohup.out
.
Ideally, you'd run your script with something like supervise
so that it can be restarted if (when) it dies.
If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.
Ctrl+Z
(suspend the process)
bg
(restart the process in the background
disown %1
(assuming this is job #1, use jobs
to determine)
You could also use GNU screen which just about every Linux/Unix system should have.
If you are on Ubuntu/Debian, its enhanced variant byobu is rather nice too.
You might consider turning your python script into a proper python daemon, as described here.
python-daemon is a good tool that can be used to run python scripts as a background daemon process rather than a forever running script. You will need to modify existing code a bit but its plain and simple.
If you are facing problems with python-daemon, there is another utility supervisor that will do the same for you, but in this case you wont have to write any code (or modify existing) as this is a out of the box solution for daemonizing processes.
You can nohup it, but I prefer screen.
Here is a simple solution inside python using a decorator:
import os, time
def daemon(func):
def wrapper(*args, **kwargs):
if os.fork(): return
func(*args, **kwargs)
os._exit(os.EX_OK)
return wrapper
@daemon
def my_func(count=10):
for i in range(0,count):
print('parent pid: %d' % os.getppid())
time.sleep(1)
my_func(count=10)
#still in parent thread
time.sleep(2)
#after 2 seconds the function my_func lives on is own
You can of course replace the content of your bgservice.py
file in place of my_func
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With