Several ways to run a Python script in the background _ basics

Source: Internet
Author: User
Tags flush sleep ssh python script in python

A monitor script, written in Python, runs all the time in test1.py, and starts the script with the following command at SSH remote (using the Putty Terminal):

Copy Code code as follows:

Python test1.py &

Now the script is working properly, through PS can see the process number, at this point directly shut down the SSH terminal (not with the Exit command, is directly through the Putty Close button to execute), log in again after the discovery process has exited.

Through the background to start the problem has been resolved, summarized here, but also convenient for me to consult later.

Linux run under the background

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

Copy Code code as follows:

#!/usr/bin/env python
Import Time,platform
Import OS

Def 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)
Except 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)
Except 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 ())

# Executing code in child processes
Funzionedemo () # function Demo

if __name__ = = ' __main__ ':
If Platform.system () = = "Linux":
Createdaemon ()
Else
Os._exit (0)

Implemented by upstart method

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

1. Write Python scripts

Copy Code code as follows:

[Root@local t27]# Cat test123.py
#!/usr/bin/env python

Import Os,time

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


2. Write Upstat configuration file
Copy Code code 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 Upstate
Copy Code code as follows:

Initctl reload-configuration

4, start the service
Copy Code code 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 09:55 0:00 python/test/t27/test123.py
Root 6677 0.0 0.0 103212 752 pts/1 s+ 09:56 0:00 grep test123.py

5. Stop Service
Copy Code code 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+ 09:56 0:00 grep test123.py
[Root@local t27]#

Implemented with bash scripts

1, Python code

Copy Code code as follows:

[Root@local test]# Cat test123.py
#!/usr/bin/env python

Import Os,time

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


2. Write startup script
Copy Code code as follows:

[Root@local test]# Cat start.sh
#! /bin/sh

Python test123.py &


3. Start process
Copy Code code as follows:

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

If you use the & START process directly:
Copy Code code as follows:

Python test123.py &

Shutting down the SSH terminal directly will cause the process to exit.

Through screen, Tmux and other ways to achieve

If you run the program temporarily, you can start the program through screen and Tmux, which describes how to start the next tmux.

1, start Tmux

Can be started with terminal input Tmux

2. Start the program in Tmux

Execute the following command directly (script reference above): Python test123.py

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

4, after the SSH up, execute the following command:

Copy Code code as follows:

Tmux Attach

Now you can see that the Python program is still running.

Background running under Windows

There is no in-depth research under Windows, and the way I often use it is to modify the Python script extension ". Pyw", double-click to run the background, do not need to modify any code.

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.