首页 > 解决方案 > 如何像运行 Windows 服务一样运行 python 服务脚本?

问题描述

我使用Pyinstaller将我的 Python 脚本转换为 exe 格式。然后我编写了另一个 python 代码来运行这个 exe,但我不想要这种方式。我想用户单击 service.exe 并且程序像 Windows 服务一样运行。我的服务代码只是检查它是否正在运行的简单示例。我的 run.exe 文件有管理代码,我的意思是你必须使用“以管理员身份运行”选项运行它。但我也不想要这种方式。有没有办法解决这些问题?

我的服务代码:


import time
from pathlib import Path
import win32serviceutil


class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = "Service"
    _svc_display_name_ = "Service"
    _svc_description_ = "a"

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):


        while self.isrunning:

            Path(f'C:\\Users\\lenovo\\Desktop\\1.txt').touch()
            time.sleep(5)
    def parse_command_line(cls):

        win32serviceutil.HandleCommandLine(cls)

if __name__ == '__main__':
    Service.parse_command_line(Service)

我运行服务的代码:


import os 
path=os.getcwd()
command='"sc create MyService binpath="'+path+'\\Service.exe" start=auto"'
os.system(command)


标签: pythonservicewindows-servicesexe

解决方案


创建一个简单的批处理脚本来启动 python 脚本。

例如:

SET PATH=%PATH%;X:\PATH_TO_PYTHON
python yourscript.py
PAUSE

只有在未设置环境变量时才需要“SET PATH...”。


推荐阅读