Python脚本作为Windows服务运行关闭控制台即停止问题咨询
问题核心原因&修复方案
你的代码和操作存在以下几处核心问题,对应修复方案如下:
SvcDoRun是Windows服务的实际执行入口,当前代码里仅监听停止事件,没有调用业务逻辑,是服务不生效的核心原因- 类方法
main没有绑定实例、也没有放入服务启动后的执行流程 - 使用相对路径读写
geek.txt,Windows服务默认工作目录为C:\Windows\System32,无法找到你预期的文件路径 - 直接用
python.exe启动服务会关联控制台窗口,窗口关闭进程就会被终止,应该用无窗口的pythonw.exe运行 - 死循环无延迟会占满单核心CPU,需要增加执行间隔
- 服务默认启动类型不是自动,系统重启后不会自动运行
第一步:替换为修正后的完整代码
import traceback import win32serviceutil import win32service import win32event import servicemanager import socket import getpass import json import pathlib import urllib.request import sys from time import time , sleep import uuid from urllib.request import urlopen , Request from urllib.parse import urlencode , quote_plus import subprocess import threading import requests from requests.sessions import session import os import cgitb import logging # 预先获取脚本所在目录的绝对路径,避免相对路径失效问题 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TARGET_FILE = os.path.join(BASE_DIR, "geek.txt") class PythonService(win32serviceutil.ServiceFramework): _svc_name_ = "PCSIGN" _svc_display_name_ = "PC SIGN" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None,0, 0, None) socket.setdefaulttimeout(60) # 新增服务运行状态控制标记 self.is_running = True def SvcStop( self ): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.is_running = False win32event.SetEvent(self.hWaitStop) def SvcDoRun( self ): # 服务启动后先执行业务逻辑 self.main() win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) def main(self): while self.is_running: # 用with语法自动管理文件句柄,避免资源泄露 with open(TARGET_FILE, 'a+', encoding='utf-8') as f: f.write("hello world\n") # 增加1秒延迟,避免CPU占满,可根据需求调整间隔 sleep(1) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PythonService)
第二步:重新安装配置服务
先清理之前安装的错误服务,再执行新的安装命令:
- 停止原有服务:
python testing.py stop - 卸载原有服务:
python testing.py remove - 用无窗口的
pythonw.exe安装服务,同时设置开机自动启动:pythonw testing.py install --startup=auto - 启动服务:
pythonw testing.py start
效果验证
- 按下
Win+R输入services.msc打开服务列表,找到PC SIGN服务,确认状态为正在运行、启动类型为自动 - 查看脚本所在目录下的
geek.txt,确认有内容持续写入 - 关闭所有Python相关窗口,服务不会停止,系统重启后会自动启动执行写入逻辑
内容的提问来源于stack exchange,提问作者programmer
相关产品推荐
相关产品推荐

