惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
C
Cybersecurity and Infrastructure Security Agency CISA
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
T
Threat Research - Cisco Blogs
C
Cisco Blogs
Recent Announcements
Recent Announcements
S
Securelist
N
Netflix TechBlog - Medium
The Register - Security
The Register - Security
P
Privacy & Cybersecurity Law Blog
宝玉的分享
宝玉的分享
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 热门话题
T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
月光博客
月光博客
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
博客园 - 司徒正美
L
LINUX DO - 最新话题
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
H
Help Net Security
Spread Privacy
Spread Privacy
PCI Perspectives
PCI Perspectives
Project Zero
Project Zero
I
Intezer
T
The Blog of Author Tim Ferriss
有赞技术团队
有赞技术团队
The Last Watchdog
The Last Watchdog
C
Check Point Blog
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
MyScale Blog
MyScale Blog
V
Vulnerabilities – Threatpost
Recorded Future
Recorded Future
T
Tenable Blog
Jina AI
Jina AI
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志

博客园 - pcwanli

Python批量将Word文档(.doc)转换为.docx格式的完整实现步骤 Linux下版本控制器(SVN) -命令行客户端 linux svn 命令 Qwen3-VL视频科技:内容审核系统搭建 svn update 出现Skipped 'feifazuzhi' -- Node remains in conflict处理方法 linux redis.service如何编写 深入php redis pconnect PHP中使用Redis长连接笔记 python happybase 批量读取 如何用phpredis持久化连接pconnect方法提升应用响应速度 python处理常见格式压缩包文件的全指南 Python编程:happybase读写HBase数据库 python redis zset 按分值获取记录 hbase日志如何清理 hbase日志清理 Python的time.strftime()方法 python re.sub第二参数,前值如何引用 python解析url参数 提取网页源码头信息的正则表达式 PHP字符串分割:explode()函数详解与应用 python requests get请求禁用自动解压 python importlib动态模块加载遇到is not a package错误,解决方法。 Python正则表达式替换(re.sub)的6种典型应用场景 用Python处理HTML转义字符的5种方式 pymongo批量更新bulk_write php mongodb操作 PHP 通过 Thrift 操作 Hbase 使用thrift的php版本操作hbase数据库 PHP通过Thrift操作Hbase
【Python】基于python实现Windows Service程序
pcwanli · 2026-03-28 · via 博客园 - pcwanli

来源:https://blog.csdn.net/ZHOU_YONG915/article/details/137787139

文章目录
0 前言
1 代码框架
2 使用方式
3 遇到的问题和解决方案
0 前言
  最近揽了一个小活,就是基于Python设计一个Windows Service程序,和一般应用不同的是,Service直接运行在后台,不会在运行时弹出黑框,因此在设计上和一般的程序有些微差别。因为之前从来没有做过这个,因此做个记录。

1 代码框架
  使用Python写Windows Service,其代码的基本框架是固定的,这也大大方便降低了入门的难度。经过查找资料,加上自己的尝试,总结出如下代码基本结构。

import servicemanager
import sys
import win32event
import win32service
import win32serviceutil

class TestService(win32serviceutil.ServiceFramework):
'''这里是一些服务的基本信息, 根据自己需要进行修改
'''
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
_svc_description_ = "My service description"

def __init__(self, args):
''' 初始化函数, 服务启动时调用, 可以用来初始化一些变量
'''
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

def SvcStop(self):
'''停止函数, 服务停止时调用, 可以用来释放资源等操作
'''
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
'''运行函数, 服务启动时调用, 可以在这里写你的代码, 注意要是一个死循环
'''
rc = None
while rc != win32event.WAIT_OBJECT_0:
###########################################
# 这里写你的代码
###########################################
with open('C:\\TestService.log', 'a') as f:
f.write('test service running...\n')
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)

def other_function(self):
'''其他函数, 可以用于写其他的代码,然后在主线程中调用
'''
pass

if __name__ == '__main__':
'''服务入口函数, 不用修改
'''
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
运行项目并下载源码
python
运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2 使用方式
  基于上述代码结构,接下来就可以根据自己需要实现的功能写代码了,和其他的开发方式没什么区别,也可以使用多线程。开发完成之后,接下来就是打包程序生成服务了,这里使用到的还是使用最为普遍的pyinstaller模块,打包指令如下

pyinstaller -F --hidden-import=win32timezone .\<文件名>.py
运行项目并下载源码
bash
1
这样就能得到一个执行程序,接下来还需要基于这个执行程序安装,运行,暂停,卸载服务等操作,基本指令如下所示。

# 安装服务
.\dist\<执行文件名>.exe install

# 启动服务
.\dist\<执行文件名>.exe start

# 停止服务
.\dist\<执行文件名>.exe stop

# 卸载服务
.\dist\<执行文件名>.exe remove
运行项目并下载源码
bash

1
2
3
4
5
6
7
8
9
10
11
到此,基本走完了开发流程,剩下的主要就是功能调试了,比较繁琐,不再赘述。

3 遇到的问题和解决方案
卸载再安装服务显示“指定的服务已标记为删除”
  这是因为在调试过程中打开了服务那个窗口导致的,所以最简单的办法就是强制删除服务之后,重启终端,然后不再在调试过程中打开服务那个窗口,如果还不行,就重启电脑试试。

实际上我的问题出在代码上面,因为我代码中服务执行部分有socket的accept函数,导致程序是堵塞执行的,所以实际上需要一定的时间这个服务也会自动删除。


————————————————
版权声明:本文为CSDN博主「记录无知岁月」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ZHOU_YONG915/article/details/137787139