Several methods for running Python scripts in the background

Source: Internet
Author: User
This article mainly introduces several methods for running Python scripts in the background, including running Python scripts in the background, upstart, bash script, screen, and tmux, you can refer to the next monitoring script test1.py written in python and run it in the while True mode. run the following command to start the script remotely (using the putty terminal) on ssh:

The code is as follows:

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

Implement 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:

The code is as follows:

#! /Usr/bin/env pythonimport time, platformimport osdef funzioneDemo (): # This is a specific business function example fout = open ('/tmp/demone. log', 'w') while True: fout. write (time. ctime () + '\ n') fout. flush () time. sleep (2) fout. close () def createDaemon (): # fork process try: if OS. fork ()> 0: OS. _ exit (0) failed t OSError, error: print 'fork #1 failed: % d (% s) '% (error. errno, error. strerror) OS. _ exit (1) OS. chdir ('/') OS. setsid () OS. umask (0) try: pid = OS. fork () if pid> 0: print 'daemon PID % d' % pid OS. _ exit (0) failed t OSError, error: print 'fork #2 failed: % d (% s) '% (error. errno, error. strerror) OS. _ exit (1) # redirect standard IO sys. stdout. flush () sys. stderr. flush () si = file ("/dev/null", 'r') so = file ("/dev/null", 'A + ') se = file ("/dev/null", 'A + ', 0) OS. dup2 (si. fileno (), sys. stdin. fileno () OS. dup2 (so. fileno (), sys. stdout. fileno () OS. dup2 (se. fileno (), sys. stderr. fileno () # execute the code funzioneDemo () # function demoif name = 'main': if platform. system () = "Linux": createDaemon () else: 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

The code is as follows:

[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.

The code is as follows:

[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.

The code is as follows:

initctl reload-configuration

4. start the service

The code is as follows:

[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

The code is as follows:

[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

The code is as follows:

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


2. Compile the startup script

The code is as follows:

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

3. start the process

The code is as follows:

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

If you directly use & start the process:

The code is as follows:

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:

The code is as follows:

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.

The above is the content of several methods for running Python scripts in the background. For more information, see PHP Chinese network (www.php1.cn )!

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.