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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles