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 &
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)
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)
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
3. Reload 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 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 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]#
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)
2. Write startup script
If Directly use & to start the process:
[root@local test]# cat start.sh#! /bin/sh python test123.py &
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
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 &
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.py3. 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)!

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.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor