简体   繁体   English

如何像运行Windows服务一样运行python服务脚本?

[英]How can I run python service script like a running windows service?

I turned my Python script to exe format using Pyinstaller .Then I write another python code to run this exe but I don't want this way. 我使用Pyinstaller将Python脚本转换为exe格式。然后我编写了另一个python代码来运行该exe,但我不想这样做。 I want to user clicks the service.exe and program runs like windows service. 我要用户单击service.exe,程序运行类似于Windows服务。 My service codes are just simple example to check if it is running or not. 我的服务代码只是检查其是否正在运行的简单示例。 My run.exe file has administrative codes I mean you have to run it with 'run as administrator' option. 我的run.exe文件具有管理代码,这意味着您必须使用“以管理员身份运行”选项来运行它。 But I don't want this way either. 但是我也不想这样。 Are there any way to solve these problems? 有什么办法可以解决这些问题?

MY SERVICE CODE: 我的服务代码:


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)

My code for running service: 我的运行服务代码:


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


Create a simple batch script to start the python script. 创建一个简单的批处理脚本以启动python脚本。

For example: 例如:

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

"SET PATH..." is only needed if the environment variable is not set. 仅当未设置环境变量时才需要“ SET PATH ...”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM