Python Script background run

Source: Internet
Author: User

Problem Description:

Environment: CentOS6.4

A monitoring script written in Python, test1.py, runs with while true and starts the script with the following command when SSH is remote (using the Putty Terminal):

python test1.py &

Now the script is working properly, through the PS can see the process number, this time directly close the SSH terminal (not with the Exit command, is directly through the Putty Close button execution), log in again after the discovery process has exited.

Through the background to start the way the problem has been resolved, here summarized below, also convenient for me to check later.

Linux under the background run by Fork implementation

In the Linux environment, the daemon is implemented by fork in C, and Python can be implemented in this way, with the sample code as follows:

#!/usr/bin/env pythonImportTime,platformImportOSdefFunzionedemo ():#This is an example of a specific business functionFout = open ('/tmp/demone.log','W')     whileTrue:fout.write (Time.ctime ()+'\ n') Fout.flush () Time.sleep (2) Fout.close ()defCreatedaemon ():#Fork Process    Try:        ifOs.fork () >0:os._exit (0)exceptOSError, 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 ()ifPID >0:Print 'Daemon PID%d'%pid os._exit (0)exceptOSError, Error:Print 'Fork #2 failed:%d (%s)'%(Error.errno, Error.strerror) os._exit (1)    #REDIRECT standard IOSys.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 ())#executing code in a child processFunzionedemo ()#function Demoif __name__=='__main__':     ifPlatform.system () = ="Linux": Createdaemon ()Else: Os._exit (0)
Through the upstart way to achieve

The application can be encapsulated as a system service via upstart, where the complete example is recorded directly.

1. Writing a Python script

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

2. Write Upstat configuration file

[[email protected] t27]# cat /etc/init/mikeTest.confdescription "My test"author "[email protected]"start on runlevel [234]stop on runlevel [0156]chdir /test/t27exec /test/t27/test123.pyrespawn

3. Reload Upstate

initctl reload-configuration

4. Start the service

[[email protected] t27]# start mikeTestmikeTest start/running, process 6635[[email protected] 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

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

Through the Bash script implementation

1. Python Code

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

2. Write the startup script

[[email protected] test]# cat start.sh#! /bin/shpython test123.py &

3. Start the process

[[email protected] test]#./start.sh

If you start the process directly with &:

python test123.py &

Shutting down the SSH terminal directly causes the process to exit.

Through screen, Tmux and other ways to achieve

If the temporary running program, you can start the program through screen, Tmux, here describes the way the Tmux start.

1. Start Tmux

在终端输入tmux即可启动

2. Start the program in Tmux

Directly execute the following command (script reference above): Python test123.py

3, directly close the SSH terminal (such as putty on the Close button);

4. After re-SSH, execute the following command:

tmux attach

Now you can see that the Python program is still performing normally.

Windows run under Background
在windows下没有深入的研究过,我经常用的方法是修改python脚本的扩展名为".pyw",双击即可后台运行,不需要修改任何代码。

Python script background run

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.