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
Follow
11 silver badge
answered Jan 9 '16 at 23:49
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
'[공부용]참고 사이트 모음 > [python]' 카테고리의 다른 글
Python (파이썬) watchdog 파일 감시 (0) | 2021.04.12 |
---|---|
[Python] Flask + uWSGI + Nginx를 연결 및 배포 (0) | 2021.04.09 |
python logging with log rotation and compression - 파이썬 시간단위 자동 로그파일 분리 및 자동 압축 (0) | 2021.03.23 |
Python Backend Program – DBModel (0) | 2021.03.23 |
[python logging] 파이썬 일단위로 로그 파일 생성하기 - 로그 파일에 자동으로 날짜 입히기 - TimedRotatingFileHandler를 이용한 데일리 로깅 (0) | 2021.03.22 |