Python writes Windows daemon program __python

Source: Internet
Author: User
Brief Introduction

Project using Python to write a monitoring program, every 5 seconds to monitor the directory, found the file immediately FTP synchronization to another server. Business requires high timeliness and high availability. To beware of a program crash, write a daemon program that monitors whether the program crashes and restarts.


Here are two ways to implement this.


The first kind of monitoring process PID mode demo.py 10 seconds to shut down program, simulate program crashes

#-*-coding:utf-8-*-Import Logging import time import OS Logging.basicconfig (Level=logging.info, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ', datefmt= '%a,%d%b%Y%H
:%m:%s ', filename= ' E:/monitor/demo.log ', filemode= ' a ') # demo.py 10 sec Shutdown program, simulation program crashes

    # Author Chubby alex 2017/09/10 class Demo:pidlogpath = "E:/monitor/pid.run" def __init__ (self): Pass 
        def setpid (self): # record process number pid fo = open (Self.pidlogpath, "w") pid = str (Os.getpid ()) Fo.write (PID) Fo.flush () Fo.close () return PID def execute (self): PID = Self.setpid () logg Ing.info ("Startup program, Process number:" + str (PID)) i = 1 while True:logging.info ("pid = + pid +"----------
        Run "+ str (i) +" s ") time.sleep (1) i + + 1 if i > 10:break Logging.info ("program shutdown ...")") If __name__ = = ' __main__ ': Demo (). Execute () 


E:/monitor/pid.run Storage demo.py Process number

monitorpid.py Monitor all process tasks in Windows system
Timed task execution, if the Run.pid process number does not exist in the system, execute the reboot command
#-*-coding:utf-8-*-import psutil import os import logging Logging.basicconfig (Level=logging.info, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ', datefmt= '%a,%d%b%Y %h:%m:%s ', filename= ' E:/monitor/monitor.log ', filemode= ' a ') # process_re = re.com Pile ("Pid=\d{1,4},\sname= ' \s{1,20}") # takes regular, gets data pid=x/xx/xxx/xxxx, name=[1~20 characters, # monitors all process service tasks on Windows system. Timed task execution, Discovery run.pid process number system does not exist, execute command python demo.py Start program # author Fat alex 2017/09/1 class monitor:pidnothandle = [] Pidl Ogpath = "E:/monitor/pid.run" def __init__ (self): Self.pidnothandle = List (Psutil.process_iter ()) # Gets the current computer's PID def getpid (self): # get process number pid fo = open (Self.pidlogpath, "r") result = Fo.read () fo.flush () Fo.close () return result def execute (self): PID = [] For each in Self.pidnothandle : a = str (each) # each isClass type, available type (each) to view type # A data style is: Psutil.

        Process (pid=0, name= ' system Idle process ') pid.append (A[15:-1]) # takes only the parentheses inside; pid=0, name= ' system Idle process ' status = 0 # Monitored program process exists state, 0 does not exist, 1 exists for all in pid:nameposition = Each.find ("name") # Get Name
            Name= ' System Idle process ' Namevalue = each[nameposition + 6:-1] # gets the name value; System Idle process Pidposition = Each.find ("pid") Pidvalue = each[pidposition + 4:nameposition-2] Print ("Name=" +nam Evalue + ", pid=" +pidvalue+ "\ n") if Pidvalue = = Self.getpid (): status = 1 pri NT ("Discovery process ==============name=" + Namevalue + ", pid=" + pidvalue + "\ n") break If status = 0: # into Process does not exist, restart program cmd = "python demo.py" Os.popen (cmd) print ("Restart program ... ...") p Rint ("Ending ...") return 0 if __name__ = = ' __main__ ': Monitor (). execUte () 

Pyinstaller monitorpid.py program to generate Monitor.exe file
Pyinstaller Baidu Experience: http://jingyan.baidu.com/article/a378c960b47034b3282830bb.html
Pyinstaller Official website: http://www.pyinstaller.org/
Execute command
E:\mywork\python\workspace\monitor>pyinstaller-w monitorpid.py info:pyinstaller:3.2.1 info:python:3.5.4 I Nfo:platform:windows-10-10.0.15063-sp0 info:wrote E:\mywork\python\workspace\monitor\MonitorPid.spec info:upx
is not available. Info:extending pythonpath with paths [' E:\\mywork\\python\\workspace\\monitor ', ' e:\\mywork\\python\\workspace\\
Monitor '] info:checking Analysis 102 info:checking Pyz 113 info:checking PKG info:building because TOC changed
Info:building PKG (CArchive) out00-pkg.pkg the info:building PKG (CArchive) out00-pkg.pkg completed. 137 Info:bootloader e:\mywork\python\soft\python35\lib\site-packages\PyInstaller\bootloader\Windows-64bit\ Runw.exe 137 info:checking exe 137 info:building because name changed 137 exe from info:building out00-exe.toc INFO : Appending archive to exe E:\mywork\python\workspace\monitor\build\MonitorPid\MonitorPid.exe info:building exe From Out00-exe.toc completed succesSfully. 144 info:checking COLLECT 145 info:building COLLECT out00-collect.toc 388 info:building COLLECT OUT00-COLLECT.TOC compl
 Eted successfully.

Package successful, anti-virus software will alarm, choose to retrieve files or add trust, the following figure is packaged after the program


set MonitorPid.exe to Windows scheduled Tasks
Windows Setup Scheduled Tasks Baidu Experience Tutorial: http://jingyan.baidu.com/article/ca00d56c767cfae99febcf73.html
Paste the core configuration screenshot:

second way of monitoring process name The first step in the same way
Pyinstaller packed demo.py into DemoServer.exePython program gets the name of the process, the most direct way is to package into EXE file
E:\mywork\python\workspace\monitor>pyinstaller-w demoserver.py info:pyinstaller:3.2.1 info:python:3.5.4 Nfo:platform:windows-10-10.0.15063-sp0 info:wrote E:\mywork\python\workspace\monitor\DemoServer.spec info:upx
is not available. Info:extending pythonpath with paths [' E:\\mywork\\python\\workspace\\monitor ', ' e:\\mywork\\python\\workspace\\ Monitor '] info:checking analysis-info:building analysis because OUT00-ANALYSIS.TOC is non existent 102 Info:ini
Tializing Module Dependency Graph ...
Info:initializing Module Graph Hooks ...
Info:analyzing Base_library.zip ... 2195 info:running Analysis Out00-analysis.toc 2196 info:adding microsoft.windows.common-controls to dependent Assemblie
S of final executable required by E:\mywork\python\soft\python35\python.exe 2595 info:caching module hooks ...
2598 info:analyzing E:\mywork\python\workspace\monitor\DemoServer.py 2825 info:loading Module hooks ... 2826 info:loading module Hook "hook-encodings.py "...
2912 info:loading module Hook "hook-xml.py" ...
3057 info:loading module Hook "hook-pywintypes.py" ...
3288 info:loading module Hook "hook-pydoc.py" ...
3304 info:looking for ctypes DLLs 3304 info:analyzing run-time hooks ... 3310 info:looking for dynamic libraries 3556 info:looking for eggs 3556 info:using Python library E:\mywork\python\soft \python35\python35.dll 3556 Info:found binding redirects: [] 3560 info:warnings to written Nitor\build\demoserver\warndemoserver.txt 3568 info:checking Pyz 3568 info:building PYZ because Out00-PYZ.toc is non exi Stent 3568 info:building Pyz (zlibarchive) E:\mywork\python\workspace\monitor\build\DemoServer\out00-PYZ.pyz 3993 Info:building Pyz (zlibarchive) E:\mywork\python\workspace\monitor\build\DemoServer\out00-PYZ.pyz completed
Successfully. 4009 info:checking PKG 4011 info:building PKG because Out00-pkg.toc is non existent 4012 info:building PKG (CArchive) o Ut00-pkg.pkg 4025 Info:buildiNg PKG (CArchive) out00-pkg.pkg completed successfully. 4028 Info:bootloader e:\mywork\python\soft\python35\lib\site-packages\PyInstaller\bootloader\Windows-64bit\ Runw.exe 4028 info:checking exe 4028 info:building exe because OUT00-EXE.TOC is non existent 4028 info:building exe fro
M Out00-exe.toc 4029 info:appending archive to EXE E:\mywork\python\workspace\monitor\build\DemoServer\DemoServer.exe
4031 info:building EXE from Out00-exe.toc completed successfully. 4036 info:checking COLLECT 4036 info:building COLLECT because Out00-collect.toc is non existent 4039 info:building COLL
 ECT out00-collect.toc 4378 info:building COLLECT Out00-collect.toc completed.

monitorpidserver.py Program
Monitor system for all process names, if no DemoServer.exe process name, execute command DemoServer.exe
#-*-coding:utf-8-*-import psutil import os import logging Logging.basicconfig (Level=logging.info, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ', datefmt= '%a,%d%b%Y %h:%m:%s ', filename= ' E:/monitor/monitor.log ', filemode= ' a ') # process_re = re.com Pile ("Pid=\d{1,4},\sname= ' \s{1,20}") # takes regular, gets data pid=x/xx/xxx/xxxx, name=[1~20 characters, # monitors all process service tasks on Windows system.
    Timed task execution, Discovery run.pid process number system does not exist, execute command python demo.py Start program # author Fat alex 2017/09/1 class Monitorserver:pidnothandle = [] ServerName = "DemoServer.exe" def __init__ (self): Self.pidnothandle = List (Psutil.process_iter ()) # Get current calculation Machine pid def execute (self): PID = [] For each in self.pidnothandle:a = str (each) # each is Class type, available type (each) to view type # A data style is: Psutil. Process (pid=0, name= ' system Idle Process ') pid.append (A[15:-1]) # takes only the parentheses inside; pid=0, name= ' system Idle process ' status = 0 # Monitored program processes exist state, 0 does not exist, 1 exists for all in pid:nameposition = Each.find (" Name ") # Gets the location of name, Name= ' System Idle Process ' Namevalue = each[nameposition + 6:-1] # gets the name value; System Idle Pr Ocess pidposition = Each.find ("pid") Pidvalue = each[pidposition + 4:nameposition-2] P
                Rint ("name=" +namevalue + ", pid=" +pidvalue+ "\ n") if namevalue = Self.servername:status = 1 Print ("Discovery process ==============name=" + Namevalue + ", pid=" + pidvalue + "\ n") Break I
            F status = = 0: # process does not exist, restart program cmd = "e:/mywork/python/workspace/monitor/dist/demoserver/" + self.servername Os.popen (cmd) print ("Restart the program ... ...") print ("Ending ...") return 0 I (")" "" "". F __name__ = = ' __main__ ': Monitorserver (). Execute ()


The fourth step of the same first way

The fifth step of the same first way
Reference Articles
How Python Gets the PID http://blog.csdn.net/ck3207/article/details/51955937 for Windows Services

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.