Home Web Front-end JS Tutorial Several ways to run Python scripts in the background

Several ways to run Python scripts in the background

Apr 01, 2017 pm 03:15 PM

A monitoring script test1.py written in python, running in while True mode, start the script through the following command when ssh remote (using putty terminal):

The code is as follows:

python test1.py &
Copy after login

Now the script is running normally and the process number can be seen through ps. At this time, the ssh terminal is closed directly (not with the exit command, but directly through putty) button executed), after logging in again, I found that the process had exited.

The problem has been solved through background startup. I will summarize it here for my future reference.

linux runs in the background

implemented through fork
In the Linux environment, the daemon process in c is implemented through fork. Python can also be implemented in this way. The sample code is as follows:

The code is as follows:

#!/usr/bin/env python
import time,platform
import os
def funzioneDemo():
    # 这是具体业务函数示例
    fout = open('/tmp/demone.log', 'w')
    while True:
        fout.write(time.ctime()+'\n')
        fout.flush()
        time.sleep(2)
    fout.close()
def createDaemon():
    # fork进程        
    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)
    # 重定向标准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())
    # 在子进程中执行代码
    funzioneDemo() # function demo
if name == 'main': 
    if platform.system() == "Linux":
        createDaemon()
    else:
        os._exit(0)
Copy after login

It is implemented through upstart method

The application can be encapsulated into a system service through upstart. The complete example is recorded directly here.

1. Write 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)
Copy after login


2. Write upstatConfiguration 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
Copy after login

3. Reload upstate

The code is as follows:

initctl reload-configuration
Copy after login

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   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
Copy after login


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+   09:56   0:00 grep test123.py
[root@local t27]#
Copy after login

Achieved 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)
Copy after login


2. Write startup script

If Directly use & to start the process:

[root@local test]# cat start.sh#! /bin/sh
python test123.py &
Copy after login

The code is as follows:

Close the ssh terminal directly, which will cause the process to exit.


Achieved through screen, tmux, etc.

[root@local test]#./start.sh
Copy after login

If you want to run the program temporarily, you can start the program through screen, tmux. Here is a description of how to start tmux.

1. Start tmux

python test123.py &
Copy after login

Enter tmux in the terminal to start

2. Start the program in tmux

Just execute the following command directly (refer to the script above): python test123.py

3. Directly close the ssh terminal (such as the close button on putty);

4. After sshing up again, execute the following command:

The code is as follows:

Now you can see that the python program is still there Execute normally.

Running in the background under windows

I have not studied it in depth under windows. The method I often use is to modify the extension of the python script to ".pyw" and double-click it. It can be run in the background without modifying any code.
The above is the content of several ways of running Python scripts in the background. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles