I successfully use:

os.killpg(process.pid, signal.SIGTERM)

Probably, you need to use subprocess module for that.

To run mongo in background use:

process = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True, preexec_fn=os.setsid
    ) 

To kill it after tests, use command I 've written first.

command - is a string contained your mongo start code, for example :

mongod --host localhost --port 27018

It works fine for me. If you will have problems wit the code, please let me know it.

Answer from Nodari L on Stack Overflow
🌐
Janakiev
janakiev.com › blog › python-background
Running a Python Script in the Background - njanakiev
April 12, 2022 - Also, don’t forget to add & so the script runs in the background: ... It is also possible to kill the process by using pkill, but make sure you check if there is not a different script running with the same name:
Discussions

asynchronous - How can i kill background python processes? - Stack Overflow
I want Python code that will give me the list of background processes running through Python itself, and kill all those processes at a time. More on stackoverflow.com
🌐 stackoverflow.com
Start a background process in Python - Stack Overflow
The original shell script starts ... in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily. ... The really duplicated question is How to launch and run external script ... More on stackoverflow.com
🌐 stackoverflow.com
how to run Python subprocess pipe in the background and then kill it - Stack Overflow
I want to get the speech synthesis program Festival to generate sound until it is killed. In Bash, what I'm trying to do would be something like the following: >cat /var/log/dmesg | festival --... More on stackoverflow.com
🌐 stackoverflow.com
How to constantly run Python script in the background on Windows? - Stack Overflow
I have created a script that moves files from one folder to another. But since the original folder is the Downloads folder I need it to always run in the background. I also have a standard Batch f... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 61153717 › how-can-i-kill-background-python-processes
asynchronous - How can i kill background python processes? - Stack Overflow
I will kill python3[11205] : python3-cimport time; time.sleep(1000)) I am not suicidal I will kill python3[15745] : <another python job running on my machine> The Python process that just does time.sleep was started by me for testing purposes in advance. ... Sign up to request clarification or add additional context in comments. ... i wanted to kill the all background async process created by python all at once, with another python program.
Top answer
1 of 11
533

While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.

Example for your case:

Copyimport subprocess
subprocess.Popen(["rm","-r","some.file"])

This will run rm -r some.file in the background. Note that calling .communicate() on the object returned from Popen will block until it completes, so don't do that if you want it to run in the background:

Copyimport subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate()  # Will block for 30 seconds

See the documentation here.

Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.

2 of 11
106

Note: This answer is less current than it was when posted in 2009. Using the subprocess module shown in other answers is now recommended in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

Copyimport os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(or, alternatively, you may try the less portable os.P_NOWAIT flag).

See the documentation here.

🌐
Chuck Grimmett
cagrimmett.com › 2016 › 05 › 06 › killing-rogue-python-processes
Identifying and killing background Python processes – Chuck Grimmett
May 6, 2016 - Here is how to identify and kill background Python processes in Terminal.app: ... 501 74440 74439 4004 0 31 0 2505592 9276 - S 0 ?? 0:00.29 python -m Simple 8:43AM 501 77045 77016 4006 0 31 0 2436888 812 - S+ 0 ttys000 0:00.00 grep python 8:57AM · The second column is the PID. Make note of which one you want to kill. Then run: ... Example. Let’s say I want to kill the python -m SimpleHTTPServer process. I see that its PID is 74440.
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › community › general discussion
Killing python script in background - Raspberry Pi Forums
ps axOT will show all processes sorted by time sudo kill -9 PID of the offending script if you have a looped process .... i.e. a script that calls the program repeatedly on exit then kill that process first then the one you want · How To ask Questions :- http://www.catb.org/esr/faqs/smart...
🌐
Delft Stack
delftstack.com › home › howto › python › python background process
Background Process in Python | Delft Stack
October 10, 2023 - The background processes are run ... also stop background processes by going to the task manager or using the Python command to kill the process using its ID....
Top answer
1 of 5
42

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.

2 of 5
8

One option is to change your script so it is intended to run continuously rather than repeatedly. Just wrap the whole thing in a while loop and add a sleep.

import time

while True:
   your_script_here
   time.sleep(300)

In order to make sure this starts up with the machine and to provide automatic restarts in the event of an exception I'd recommend making it into a Windows service using Non-Sucking Service Manager (www.nssm.cc). There are a few steps to this (see the docs) but once done your script will be just another windows service which you can start and stop from the standard services.msc utility.

Top answer
1 of 2
4

As far as I know, there are just two (or maybe three or maybe four?) solutions to the problem of running background scripts on remote systems.

1) nohup

nohup python -u myscript.py > ./mylog.log  2>&1 &

1 bis) disown

Same as above, slightly different because it actually remove the program to the shell job lists, preventing the SIGHUP to be sent.

2) screen (or tmux as suggested by neared)

Here you will find a starting point for screen.

See this post for a great explanation of how background processes works. Another related post.

3) Bash

Another solution is to write two bash functions that do the job:

mynohup () {
    [[ "$1" = "" ]] && echo "usage: mynohup python_script" && return 0
    nohup python -u "$1" > "${1%.*}.log" 2>&1 < /dev/null &
}

mykill() {
    ps -ef | grep "$1" | grep -v grep | awk '{print $2}' | xargs kill
    echo "process "$1" killed"
}

Just put the above functions in your ~/.bashrc or ~/.bash_profile and use them as normal bash commands.

Now you can do exactly what you told:

mynohup myscript.py             # will automatically continue running in
                                # background even if I log out

# two days later, even if I logged out / logged in again the meantime
mykill myscript.py

4) Daemon

This daemon module is very useful:

python myscript.py start

python myscript.py stop
2 of 2
1

Do you mean log in and out remotely (e.g. via SSH)? If so, a simple solution is to install tmux (terminal multiplexer). It creates a server for terminals that run underneath it as clients. You open up tmux with tmux, type in your command, type in CONTROL+B+D to 'detach' from tmux, and then type exit at the main terminal to log out. When you log back in, tmux and the processes running in it will still be running.

🌐
GeeksforGeeks
geeksforgeeks.org › python › running-python-program-in-the-background
Running Python program in the background - GeeksforGeeks
August 21, 2020 - You can use it by running the following line on the terminal: ... In Linux and mac, for running py files in the background you just need to add & sign after using command it will tell the interpreter to run the program in the background ...
🌐
Stack Overflow
stackoverflow.com › questions › 77600221 › properly-run-and-kill-background-process-in-a-python-script-pytest
subprocess - Properly run and kill background process in a python script/pytest - Stack Overflow
In the end I obtained the desired behavior through the sid + calling another shell to terminate since there's no os.killsession method · with Popen(CMD, shell=False, start_new_session=True) as proc: func() call(['pkill', '-9', '-s', str(os.getsid(proc.pid))]) However, calling pkill -9 like that sounds rather extreme and I have the intuition there should be a cleaner way to do this. So I'm making this post to know if there are recommended patterns to run a shell command in the background alongside a python script then properly terminate it with all its children.
🌐
MSFT Stack
msftstack.wordpress.com › 2019 › 04 › 20 › how-to-kill-processes-with-python
How to kill processes using Python | MSFT Stack
April 20, 2019 - Sometimes you need to kill processes ... out some background tasks in a hurry. Killing processes, particularly on Windows, can be a bit of a manual process. There are command line programs like taskill.exe, but it’s useful to be able to combine process killing with a programming language like Python which lets you easily add pattern matching to selectively pick the processes. Let’s go through the steps of listing, matching, and killing processes running on the ...
🌐
Reddit
reddit.com › r/learnpython › how to kill a process from python?
r/learnpython on Reddit: How to kill a process from python?
November 20, 2020 -

So i want to make a little deamon who monitor the processes in windows. I know from cmd i would usually use tasklist. Then if xyz.exe is running, i want to kill it (taskkill /IM xyz.exe /f" im starting at programming and i have no clue how to do this. Plus i would like it to check every 5 minute for that process, and i want it to run in background without being in the taskbar. Someone could point me in the right direction?

Edit: it will run in Win10