Python Windows服务
开发环境:python3.7
import引用
Python 全选
import sys
import os
import signal
import win32serviceutil
import win32service
import win32event
import logging
import inspect
import servicemanager
服务代码
Python 全选
class SeoService(win32serviceutil.ServiceFramework):
_svc_name_ = "SeoService" # 服务名
_svc_display_name_ = "_SEO排名后台接口" # 服务在windows系统中显示的名称
_svc_description_ = "IP+UA接口" # 服务的描述
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.logger = self._getLogger()
self.run = True
def _getLogger(self):
logger = logging.getLogger('[SeoService]')
this_file = inspect.getfile(inspect.currentframe())
dirpath = os.path.abspath(os.path.dirname(this_file))
handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
def SvcDoRun(self):
self.logger.info("service is run....")
# 服务运行
app.run(host='0.0.0.0', port=9800)
# while self.run:
# self.logger.info("I am runing....")
# time.sleep(2)
def SvcStop(self):
self.logger.info("service is stop....")
os.kill(os.getpid(), signal.SIGINT)
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.run = False
if __name__ == '__main__':
if len(sys.argv) == 1:
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(SeoService) # 如果修改过名字,名字要统一
servicemanager.Initialize('SeoService',
evtsrc_dll) # 如果修改过名字,名字要统一
servicemanager.StartServiceCtrlDispatcher()
except win32service.error as details:
import winerror
if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(SeoService)
Py文件运行 服务管理
#1.安装服务
PowerShell 全选
python PythonService.py install
#2.让服务自动启动
PowerShell 全选
python PythonService.py --startup auto install
#3.启动服务
PowerShell 全选
python PythonService.py start
#4.重启服务
PowerShell 全选
python PythonService.py restart
#5.停止服务
PowerShell 全选
python PythonService.py stop
#6.删除/卸载服务
PowerShell 全选
python PythonService.py remove
将py文件打包为exe
PowerShell 全选
pyinstaller -F apiServer.py
pyinstaller参数说明
Python pyinstaller 打包参数说明 - 文章随笔 - YES开发框架网 (yesdotnet.com)
打包exe文件运行 服务管理
参数和py运行差不多,
#1.安装服务
PowerShell 全选
.\apiServer.exe install
#2.让服务自动启动
PowerShell 全选
.\apiServer.exe --startup auto install
#3.启动服务
PowerShell 全选
.\apiServer.exe start
#4.重启服务
PowerShell 全选
.\apiServer.exe restart
#5.停止服务
PowerShell 全选
.\apiServer.exe stop
#6.删除/卸载服务
PowerShell 全选
.\apiServer.exe remove
问题:
python服务用pyinstall打包exe后,安装服务时报错
命令 .\apiServer.exe install 报错信息
PS E:\GZ\Python\gz\dist> .\apiServer.exe install
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'win32timezone'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 980, in _find_and_load
SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "apiServer.py", line 221, in <module>
File "win32serviceutil.py", line 695, in HandleCommandLine
File "win32serviceutil.py", line 612, in GetServiceClassString
File "<frozen importlib._bootstrap>", line 980, in _find_and_load
SystemError: <class '_frozen_importlib._ModuleLockManager'> returned a result with an error set
[20284] Failed to execute script 'apiServer' due to unhandled exception!
解决方案
安装pypiwin32包
PowerShell 全选
pip install pywin32
代码中添加 引用
Python 全选
import win32timezone
不用考虑代码中有没有用到这个引用,不添加的话虽然生成exe不会报错,运行的时候就会报错了
Markup 全选
Package Version
------------------------- ----------
absl-py 0.15.0
altgraph 0.17.2
argcomplete 1.12.3
argon2-cffi 21.1.0
asgiref 3.3.4
astunparse 1.6.3
attrs 21.2.0
backcall 0.2.0
bleach 4.1.0
blinker 1.4
Brotli 1.0.9
cached-property 1.5.2
cachetools 4.2.4
certifi 2021.5.30
cffi 1.15.0
charset-normalizer 2.0.6
clang 5.0
click 7.1.2
colorama 0.4.4
cryptography 3.2.1
debugpy 1.5.1
decorator 5.1.0
defusedxml 0.7.1
entrypoints 0.3
et-xmlfile 1.1.0
fake-useragent 0.1.11
flake8 3.9.2
Flask 1.1.4
flatbuffers 1.12
future 0.18.2
gast 0.4.0
google-auth 2.3.3
google-auth-oauthlib 0.4.6
google-pasta 0.2.0
grpcio 1.41.1
h11 0.12.0
h2 4.1.0
h5py 3.1.0
hpack 4.0.0
hyperframe 6.0.1
idna 3.2
importlib-metadata 4.8.1
importlib-resources 5.4.0
ipykernel 6.5.0
ipython 7.29.0
ipython-genutils 0.2.0
ipywidgets 7.6.5
itsdangerous 1.1.0
jedi 0.18.0
jieba 0.42.1
Jinja2 2.11.3
jsonschema 4.2.0
jupyter 1.0.0
jupyter-client 7.0.6
jupyter-console 6.4.0
jupyter-core 4.9.1
jupyterlab-pygments 0.1.2
jupyterlab-widgets 1.0.2
kaitaistruct 0.9
keras 2.6.0
Keras-Preprocessing 1.1.2
ldap3 2.8.1
Markdown 3.3.4
MarkupSafe 2.0.1
matplotlib-inline 0.1.3
mccabe 0.6.1
mistune 0.8.4
mitmproxy 5.3.0
msgpack 1.0.2
nbclient 0.5.4
nbconvert 6.2.0
nbformat 5.1.3
nest-asyncio 1.5.1
notebook 6.4.5
numpy 1.19.5
oauthlib 3.1.1
openpyxl 3.0.9
opt-einsum 3.3.0
packaging 21.2
pandocfilters 1.5.0
parso 0.8.2
passlib 1.7.4
pefile 2021.9.3
pickleshare 0.7.5
pip 21.3.1
prometheus-client 0.12.0
prompt-toolkit 3.0.22
protobuf 3.13.0
publicsuffix2 2.20191221
pyasn1 0.4.8
pyasn1-modules 0.2.8
pycodestyle 2.7.0
pycparser 2.20
pydivert 2.1.0
pyflakes 2.3.1
Pygments 2.10.0
pyinstaller 4.5.1
pyinstaller-hooks-contrib 2021.3
pymssql 2.2.2
pyodbc 4.0.32
pyOpenSSL 19.1.0
pyparsing 2.4.7
pyperclip 1.8.2
pyrsistent 0.18.0
python-dateutil 2.8.2
pywin32 302
pywin32-ctypes 0.2.0
pywinpty 1.1.5
PyYAML 5.4.1
pyzmq 22.3.0
qtconsole 5.1.1
QtPy 1.11.2
regex 2021.11.2
requests 2.26.0
requests-oauthlib 1.3.0
rsa 4.7.2
ruamel.yaml 0.16.13
ruamel.yaml.clib 0.2.6
selenium 3.141.0
Send2Trash 1.8.0
sentencepiece 0.1.96
setuptools 58.5.2
six 1.15.0
sortedcontainers 2.2.2
tensorboard 2.7.0
tensorboard-data-server 0.6.1
tensorboard-plugin-wit 1.8.0
tensorflow 2.6.1
tensorflow-estimator 2.6.0
tensorflow-hub 0.12.0
termcolor 1.1.0
terminado 0.12.1
testpath 0.5.0
torch 1.10.0
tornado 6.1
traitlets 5.1.1
typing-extensions 3.7.4.3
urllib3 1.26.7
urwid 2.1.2
wcwidth 0.2.5
webencodings 0.5.1
Werkzeug 1.0.1
wheel 0.37.0
widgetsnbextension 3.5.2
wrapt 1.12.1
wsproto 0.15.0
xlrd 1.2.0
yapf 0.31.0
zipp 3.6.0
zstandard 0.14.1
问题:python重新生成exe后,无法启动服务了,1053
运行生成exe语句 ,之前,删除
Python 全选
pyinstaller -F apiServer.py
删除图中标识的三个目录或文件,_pycache_,build,apiServer.spec
删除后重新生成exe,问题或许就能解决
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员