본문 바로가기

[공부용]참고 사이트 모음/[python]

Starting/stopping a background Python process wtihout nohup + ps aux grep + kill

stackoverflow.com/questions/34687883/starting-stopping-a-background-python-process-wtihout-nohup-ps-aux-grep-kill

 

Starting/stopping a background Python process wtihout nohup + ps aux grep + kill

I usually use: nohup python -u myscript.py &> ./mylog.log & # or should I use nohup 2>&1 ? I never remember to start a background Python process that I'd like to continue

stackoverflow.com

 

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

Share

Follow

edited May 23 '17 at 11:46

Community

11 silver badge

answered Jan 9 '16 at 23:49

terence hill

3,10411 silver badges28 bronze badges

  •  
  • Is it possible to make such a bash function myrun that will be used with myrun script.py that 1) reads the first line of script.py, remove the leading #MYRUN: 2) execute the command written in this first line. Example: doing myrun script.py with this file will execute nohup python -u script.py &. – Basj Jan 16 '16 at 16:05
  •  
  • I started a question about this here stackoverflow.com/questions/34829145/… – Basj Jan 16 '16 at 16:19
  • 1
  • I now use screen and that's awesome and simple. screen -s myscript, then run the script python myscript.py then detach with CTRL+A, D, then I can log out etc. To reattach screen -r myscript, that's it! – Basj Dec 7 '16 at 12:17