• Windows环境中Python应用服务自启动及其监控解决方法


    需求描述:

    • 在windows服务器环境中,python应用服务在服务器重启时,能自动启动;
    • 在任务管理器中,能区分监控python应用服务(默认都是python的情况,无法区分多个python进程);
    • 监控python应用服务进程,当应用服务挂掉后,重新启动服务。

    1. Python应用服务自启动

    1.1. 启动时运行批处理文件

    Windows 10/Windows Server 201X具有一个名为“启动”的已知文件夹,系统每次启动开始自动运行应用程序、快捷方式和脚本时都会检查该文件夹,而无需额外配置。

    要在Windows启动时运行脚本,先使用Windows+R快捷键打开“运行”对话框。
    在这里插入图片描述

    键入命令:shell:startup

    C:\Users\xiaoyw\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
    
    • 1

    写段测试代码,做成批处理,放到“启动”文件夹下。
    在这里插入图片描述

    批处理,命名为startup.bat:

    d:
    cd \01workspace\study
    python TestStartup.py
    
    • 1
    • 2
    • 3

    python示例代码:

    import datetime
    
    now = datetime.datetime.now()
    dtime = now.strftime("%Y-%m-%d %H:%M:%S")
    print('延迟时间是:', dtime)
    
    with open('startup.txt','w') as f:
        f.write(dtime + ", test ok!")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.2. 使用任务计划程序运行批处理文件

    使用任务计划程序在特定时间自动运行批处理文件。
    在这里插入图片描述

    1.3. 注册服务

    注册服务的优势就在于可以开机自启动,而在windows上,python不能直接将脚本注册为服务,需要将其先打包成exe,再将exe注册为服务。

    打包exe,使用pyinstaller打包,安装好pyinstaller包后,在cmd/pycharm的终端里运行如下代码打包。

    2. 应用服务监控

    2.1. 自定义python脚本在windows下的进程名

    在windows环境中,部署多个python应用服务时,在任务管理器中监控进程时,任务名称都是python.exe,无法识别是哪个具体任务,造成维护困难。
    在这里插入图片描述
    简单解决方法是按需拷贝(copy)python.exe文件(python.exe大小只有100k),然后重命名成为pvforecast_py.exe(或者随便你想要的名字),然后你写一个批处理文件,内容是start python_myapp1.exe myapp.py。然后你运行批处理文件,你就会发现在任务管理器中的详细信息页面中出现了python_myapp1.exe。python.exe大小只有几十k,多copy几个也无所谓。比起build成exe还是简单很多。

    批处理文件名称为PVForecastAPScheduler.bat,代码如下:

    @echo off
    D:
    cd D:\Python\PVMicrogrid\PVSystem
    start pvforecast_py PVForecastAPScheduler.py
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述
    测试验证代码如下:

    import datetime
    import pytz
    from apscheduler.schedulers.blocking import BlockingScheduler
    
    def test():
        now = datetime.datetime.now()
        dtime = now.strftime("%Y-%m-%d %H:%M:%S")
        print('延迟时间是:', dtime)
    
        with open('startup1.txt','w') as f:
            f.write(dtime + ", test ok!")
        
    scheduler = BlockingScheduler(timezone=pytz.timezone("Asia/Shanghai") )
    
    
    scheduler.add_job(test, 'cron', second='10', misfire_grace_time=60, id='job1')
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2.2. 守护进程

    有时会遇到断网、硬件设备掉线等情况,需要重新启动服务,觉得较为麻烦。想仿照linux下的脚本,写一个windows下的脚本,守护进程,自动检查自启动,或发出报警。

    windows下的脚本为monitor.bat文件,下面以启动***.exe文件为例:

    @echo off
    :start
    choice /t 5 /d y /n >nul
    tasklist|find /i "pvforecast_py.exe"
    if %errorlevel%==0 (
    echo "yes"
    ) else (
    echo "No"
    start pvforecast_py.exe  ****.py
    )
    goto start
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    其中,

    	###定时5s
    	choice /t 5 /d y /n >nul     
    	 ###如果存在该进程
    	if %errorlevel%==0 ( 
    	###如果不存在,则自行启动
    	start pvforecast_py.exe  ****.py
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3. 把应用程序与批处理文件加入到安全白名单中

    加入到白名单中的文件目录,文件,安全防护工具将信任该软件,可以直接使用。以360安全卫士为例,在信任区添加python文件目录,以及启动文件夹中的批处理文件。
    在这里插入图片描述

    4. 实践方案

    最初,使用任务计划程序方式,自动启动python应用服务,由于受到安全卫士的阻止,没有找到易操作维护任务计划程序方式,现改为在启动中部署自动启动python用于服务,以及增加监控方法,提高运维效率。

    最后的批处理文件(buildw.bat)如下:

    chcp 65001
    copy d:\python\python38\python.exe d:\python\python38\pvforecast_py.exe
    copy d:\python\python38\python.exe d:\python\python38\pvweather24_py.exe
    copy d:\python\python38\python.exe d:\python\python38\pvweather_py.exe
    copy d:\python\python38\python.exe d:\python\python38\pvenergy_py.exe
    
    copy D:\Python\PVMicrogrid\PVSystem\PVForecastAPScheduler.bat "%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\PVForecastAPScheduler.bat"
    copy D:\Python\PVMicrogrid\PVSystem\PVTrainAPScheduler.bat "%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\PVTrainAPScheduler.bat"
    copy D:\Python\PVMicrogrid\PVSystem\PVAPScheduler.bat "%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\PVAPScheduler.bat"
    copy D:\Python\PVMicrogrid\EnergyOptimization\EnergyAPScheduler.bat "%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\EnergyAPScheduler.bat"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    以管理员身份进入CMD命令行窗口:

    	D:\>buildw.bat
    
    • 1

    相关批处理命令解释如下:

    注:在 Windows 批处理中,如果路径中含有中文字符,可能会出现乱码的情况。
    在批处理文件开头添加以下语句:
    chcp 65001
    这个命令可以将命令行窗口的字符编码设置为 UTF-8,从而支持中文字符。

    注:如果文件路径中含有空格,则批处理命令中,使用双引号引起来。

    5. 其他

    也可以使用所有用户的启动目录:

    C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
    
    • 1

    用管理员权限用户启动目录,所有用户的启动目录,批处理都执行。


    参考:

    cnolnic. python 开机自启 python程序自启动. 51CTO博客. 2023.10

    狗蛋的博客之旅. 快速入门 Windows 批处理编写:无需编程经验. CSDN博客. 2023.05

  • 相关阅读:
    eclipse中如何把中文变成英文?
    PSO粒子群优化算法
    很建议学习的Linux软件包管理— 软件包分类
    Flink container exit 143 问题排查
    excel实战应用案例100讲(十一)-Excel插入图片小技巧
    【论文爬虫】自动将论文详细信息直送notion并自动下载(含源码)
    SSH远程访问开发板
    idea插件generateAllSetMethod一键生成set/get方法以及bean对象转换
    python毕业设计作品基于django框架 疫苗预约系统毕设成品(8)毕业设计论文模板
    大数据 - HBase《一》- Hbase基本概念
  • 原文地址:https://blog.csdn.net/xiaoyw/article/details/134500228