Several Methods for running Python scripts in the background

Source: Internet
Author: User

Several Methods for running Python scripts in the background

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, for more information, see

 

 

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:

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 python
Import time, platform
Import OS

 

Def funzioneDemo ():
# This is an example of a specific business function
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)
# Redirection 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 code in the sub-process
FunzioneDemo () # function demo

If _ 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 python

 

Import OS, time

While 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. conf
Description "My test"
Author "Mike_Zhang@live.com"

 

Start on runlevel [234]
Stop on runlevel [0156]

Chdir/test/t27
Exec/test/t27/test123.py
Respawn


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 mikeTest
MikeTest start/running, process 6635
[Root @ local t27] # ps aux | grep test123.py
Root 6635 0.0 0.0 22448 3716? Ss python/test/t27/test123.py
Root 6677 0.0 0.0 103212 752 pts/1 S + grep test123.py


5. Stop the service

The Code is as follows:


[Root @ local t27] # stop mikeTest
MikeTest stop/waiting
[Root @ local t27] # ps aux | grep test123.py
Root 6696 0.0 0.0 103212 752 pts/1 S + 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 python

 

Import OS, time

While True:
Print time. time ()
Time. sleep (1)


2. Compile the Startup Script

The Code is as follows:


[Root @ local test] # cat start. sh
#! /Bin/sh

 

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

Related Article

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.