python - 如何像运行 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)
解决方案
创建一个简单的批处理脚本来启动 python 脚本。
例如:
SET PATH=%PATH%;X:\PATH_TO_PYTHON
python yourscript.py
PAUSE
只有在未设置环境变量时才需要“SET PATH...”。
推荐阅读
- bigcommerce - 产品的 Bigcommerce 复选框插件
- netsuite - 登录审计跟踪保存的搜索
- visual-studio-code - 支持 VS 代码扩展 DLT 日志的 DLT 二进制文件
- powerbi - 查找第二个日期的 DAX 公式 - Power BI
- design-patterns - 将单词和模式之间的行移动到文件末尾
- sql - SQL oracle 检查可用日期
- excel - 如果列标题匹配,如何将数据从 csv 表复制到 excel 表
- rust - 如何在 Rust 的串行端口箱中使用 read_line 函数
- css - 强制图像匹配 Tailwind 中父 flexbox 的尺寸
- locale - 设置 Altair FormatLocale 不起作用