Python scripts run in the background and python scripts run in the background

Source: Internet
Author: User

Python scripts run in the background and python scripts run in the background

Problem description:

Environment: CentOS6.4

A monitoring script test1.py written in python is always running in the while True mode. Run the following command to start the script remotely (using the putty terminal) in ssh:

python test1.py &

Now that the script runs normally, you can see the process number through ps. In this case, close the ssh terminal directly (instead of using the exit command, it is executed directly through the close button of putty ), after logging on again, you will find that the process has exited.

This problem has been solved through the background startup method, which is summarized here for future reference.

Running in linux background is implemented through fork

In linux, the daemon in c is implemented through the fork method, and python can also be implemented through this method. The sample code is as follows:

1 #! /Usr/bin/env python 2 # E-Mail: Mike_Zhang@live.com 3 import time, platform 4 import OS 5 6 def funzioneDemo (): 7 # This is an example of a specific business function 8 fout = open ('/tmp/demone. log', 'w') 9 while True: 10 fout. write (time. ctime () + '\ n') 11 fout. flush () 12 time. sleep (2) 13 fout. close () 14 15 def createDaemon (): 16 # fork process 17 try: 18 if OS. fork ()> 0: OS. _ exit (0) 19 failed t OSError, error: 20 print 'fork #1 failed: % d (% s) '% (error. errno, error. strerror) 21 OS. _ exit (1) 22 OS. chdir ('/') 23 OS. setsid () 24 OS. umask (0) 25 try: 26 pid = OS. fork () 27 if pid> 0: 28 print 'daemon PID % d' % pid29 OS. _ exit (0) 30 failed t OSError, error: 31 print 'fork #2 failed: % d (% s) '% (error. errno, error. strerror) 32 OS. _ exit (1) 33 # redirection standard IO34 sys. stdout. flush () 35 sys. stderr. flush () 36 si = file ("/dev/null", 'R') 37 so = file ("/dev/null", 'a + ') 38 se = file ("/dev/null", 'a + ', 0) 39 OS. dup2 (si. fileno (), sys. stdin. fileno () 40 OS. dup2 (so. fileno (), sys. stdout. fileno () 41 OS. dup2 (se. fileno (), sys. stderr. fileno () 42 43 # Execute Code 44 funzioneDemo () # function demo45 46 if _ name _ = '_ main _' in the sub-process __': 47 if platform. system () = "Linux": 48 createDaemon () 49 else: 50 OS. _ exit (0)

 

Implemented through upstart

 

You can use upstart to encapsulate an application into a system service. The complete example is recorded here.

1. Compile a python script

[root@local t27]# cat test123.py#!/usr/bin/env pythonimport os,timewhile True :    print time.time()    time.sleep(1)

2. Compile the upstat configuration file.

[root@local t27]# cat /etc/init/mikeTest.confdescription "My test"author "Mike_Zhang@live.com"start on runlevel [234]stop on runlevel [0156]chdir /test/t27exec /test/t27/test123.pyrespawn

3. Reload the upstate.

initctl reload-configuration

4. Start the service

[root@local t27]# start mikeTestmikeTest start/running, process 6635[root@local t27]# ps aux | grep test123.pyroot      6635  0.0  0.0  22448  3716 ?        Ss   09:55   0:00 python /test/t27/test123.pyroot      6677  0.0  0.0 103212   752 pts/1    S+   09:56   0:00 grep test123.py

5. Stop the service

[root@local t27]# stop mikeTestmikeTest stop/waiting[root@local t27]# ps aux | grep test123.pyroot      6696  0.0  0.0 103212   752 pts/1    S+   09:56   0:00 grep test123.py[root@local t27]#

Implemented through bash script

1. python code

[root@local test]# cat test123.py#!/usr/bin/env pythonimport os,timewhile True :    print time.time()    time.sleep(1)

2. Compile the Startup Script

[root@local test]# cat start.sh#! /bin/shpython test123.py &

3. Start the process

[root@local test]#./start.sh

If you directly use & start the process:

python test123.py &

Shutting down ssh hosts directly causes the process to exit.

 

Implemented through screen, tmux, and other methods

If you run the program temporarily, you can use screen and tmux to start the program. Here we describe how tmux starts.

1. Start tmux

Enter tmux on the terminal to start

2. Start the program in tmux

Run the following command directly (for the script, refer to the above): python test123.py

3. Directly close the ssh terminal (for example, the close button on putty );

4. Run the following command after reinstalling ssh:

tmux attach

Now we can see that the python program is still running normally.

 

Running in windows Background
I have not studied it in depth in windows. I often use the method of modifying the python script extension to ". pyw". Double-click it to run it in the background without any code modification.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.