Run a Program from Python, and Have It Continue to Run After the Script Is Killed

Run a program from python, and have it continue to run after the script is killed

The usual way to do this on Unix systems is to fork and exit if you're the parent. Have a look at os.fork() .

Here's a function that does the job:

def spawnDaemon(func):
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# parent process, return and keep running
return
except OSError, e:
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)

os.setsid()

# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)

# do stuff
func()

# all done
os._exit(os.EX_OK)

How to immediately kill Python script after running subprocess?

Don't use subprocess.run; use os.execl instead. That makes your media player replace your Python code in the current process, rather that starting a new process.

os.execl(MEDIA_PLAYER, p)

subprocess.run effectively does the same thing, but forks first so that there are temporarily two processes running your Python script; in one, subprocess.run returns without doing anything else to allow your script to continue. In the other, it immediately uses one of the os.exec* functions—there are 8 different varieties—to execute your media player. In your case, you just want the first process to exit anyway, so save the effort of forking and just use os.execl right away.

python script calling a shell script and i want to keep its process active even if the python script ends

You can do it by using subprocess.Popen.

Something like this:

main.py

import subprocess

print("Starting")
subprocess.Popen(["sh", "child.sh"])
print("Ending")

child.sh

while :
do
echo "Something"
sleep 1
done

The script will continue printing even after the process is finished.

How to stop/terminate a python script from running?

To stop your program, just press Control + C.

How to constantly run Python script in the background on Windows?

On Windows, you can use pythonw.exe in order to run a python script as a background process:

Python scripts (files with the extension .py) will be executed by
python.exe by default. This executable opens a terminal, which stays
open even if the program uses a GUI. If you do not want this to
happen, use the extension .pyw which will cause the script to be
executed by pythonw.exe by default (both executables are located in
the top-level of your Python installation directory). This suppresses
the terminal window on startup.

For example,

C:\ThanosDodd\Python3.6\pythonw.exe C:\\Python\Scripts\moveDLs.py

In order to make your script run continuously, you can use sched for event scheduling:

The sched module defines a class which implements a general purpose
event scheduler

import sched
import time

event_schedule = sched.scheduler(time.time, time.sleep)

def do_something():
print("Hello, World!")
event_schedule.enter(30, 1, do_something, (sc,))

event_schedule.enter(30, 1, do_something, (s,))
event_schedule.run()

Now in order to kill a background process on Windows, you simply need to run:

taskkill /pid processId /f

Where processId is the ID of the process you want to kill.

Run a process and kill it if it doesn't end within one hour

The subprocess module will be your friend. Start the process to get a Popen object, then pass it to a function like this. Note that this only raises exception on timeout. If desired you can catch the exception and call the kill() method on the Popen process. (kill is new in Python 2.6, btw)

import time

def wait_timeout(proc, seconds):
"""Wait for a process to finish, or raise exception after timeout"""
start = time.time()
end = start + seconds
interval = min(seconds / 1000.0, .25)

while True:
result = proc.poll()
if result is not None:
return result
if time.time() >= end:
raise RuntimeError("Process timed out")
time.sleep(interval)


Related Topics



Leave a reply



Submit