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 OverflowI 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.
You can also do this in straight bash with jobs and traps:
#!/bin/bash
trap "kill %1" SIGINT SIGTERM EXIT
mongod --host localhost --port 27018 &
istanbul cover node_modules/mocha/bin/_mocha -- -R spec
exit 0
What this is doing:
- Set a trap on signals, SIGINT SIGTERM EXIT, to kill the first backgrond job
- Make a mongod instance, and throw it into the background (the first one)
- Run the tests
- trigger exit signal
So this will setup and tare down your mongod instance on completion, even on a term signal or exception.
asynchronous - How can i kill background python processes? - Stack Overflow
Start a background process in Python - Stack Overflow
how to run Python subprocess pipe in the background and then kill it - Stack Overflow
How to constantly run Python script in the background on Windows? - Stack Overflow
You will have to find the process id (pid). one command to do this would be
$> ps -ef
to limit results to python processes you can grep the result
$> ps -ef | grep python
which will give results like :
user 2430 1 0 Jul03 ? 00:00:01 /usr/bin/python -tt /usr/sbin/yum-updatesd
the second column is the pid. then use the kill command as such :
$> kill -9 2430 (i.e. the pid returned)
Try this simple line, It will terminate all script.py:
pkill -9 -f script.py
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.
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.
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 bypython.exeby 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.pywwhich will cause the script to be executed bypythonw.exeby 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.
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.
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
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.
Use the shebang line in your python script. Make it executable using the command,
chmod +x test.py
Use no hangup to run the program in the background even if you close your terminal,
nohup /path/to/test.py &
or simply (without making any change in your program)
nohup python /path/to/test.py &
Do not forget to use & to put it in the background.
Role of nohup: nohup makes your script ignore SIGHUP, and redirects stdout/stderr to a file nohup.out, so that the command can continue running in the background after you log out. If you close the shell/terminal or log off, your command is no longer a child of that shell. It belongs to init process. If you search in pstree you'll see it is now owned by process 1 (init).
To see the process again, use in terminal,
ps ax | grep test.py
That cannot be brought back to the foreground because the foreground (as the terminal already closed) no longer exists. So there is no way to get that terminal back again once it is closed.
python test.py &
will run the file in the background.
In order to find the running program, you can use ps -e to list all running programs. You can use grep to find your particular program from the list.
Im using pyautogui to automate something when it clicks on the program its supposed to automate it stops nd only runs when my python intrepter is the current tab
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