Windows에서 Python script as a Service를 실행하는 방법은 무엇입니까?
데이터베이스에 저장된 다양한 상호 관련 개체를 공유하는 프로그램 세트를 위한 아키텍처를 스케치하고 있습니다.프로그램 중 하나는 이러한 오브젝트에 대한 조작을 위한 보다 높은 수준의 인터페이스를 제공하는 서비스로서 기능하고, 다른 프로그램은 그 서비스를 통해 오브젝트에 액세스 할 수 있도록 하고 싶다.
현재 Python과 Django Framework를 목표로 하고 있습니다.Linux에서 Python 프로그램을 데몬화하는 방법을 알고 있습니다.다만, 시스템이 Windows 를 서포트하는 것은 옵션의 사양 항목입니다.저는 Windows 프로그래밍에 대한 경험이 거의 없고 Windows 서비스에 대한 경험이 전혀 없습니다.
Python 프로그램을 Windows 서비스로 실행할 수 있습니까(즉, 사용자 로그인 없이 자동으로 실행)?꼭 이 부분을 구현할 필요는 없지만, 이 부분에 따라 설계할지를 결정하기 위해서는 대략적인 아이디어가 필요합니다.
편집: 지금까지의 답변은 매우 포괄적입니다.한 가지 더 알고 싶은 게 있어요.Windows에서 서비스를 인식하는 방법 Windows의 네이티브 유틸리티로 관리할 수 있습니까?/etc/init.d에 start/stop 스크립트를 넣는 것과 동등한 것은 무엇입니까?
네, 가능합니다.ActivePython에 포함되어 있거나 pywin32(Windows 확장용 Python)에 설치 가능한 pythoncom 라이브러리를 사용합니다.
이것은 단순한 서비스의 기본 골격입니다.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
의 는 ★★★★★★★★★★★★★★★★★★★★★★★★★★」main()
method:수 있는 루프는, 「Method」로 설정합니다.이러한 루프는SvcStop
가장 간단한 방법은 NSSM(Non-Seeking Service Manager)을 사용하는 것입니다.원하는 위치에 다운로드하여 압축을 풀기만 하면 됩니다.이 유틸리티는 약 300KB(이 용도로만 pywin32 스위트 전체를 설치하는 것보다 훨씬 작음)로, 「설치」는 불필요합니다.zip에는 64비트 및 32비트 버전의 유틸리티가 포함되어 있습니다.둘 중 하나가 현재 시스템에서 제대로 작동해야 합니다(32비트 버전을 사용하여 64비트 시스템의 서비스를 관리할 수 있습니다).
GUI 어프로치
1 - python 프로그램을 서비스로 설치합니다.Win 프롬프트를 admin으로 엽니다.
c:\>nssm.exe install WinService
2 - NSSM의 GUI 콘솔:
경로: C:\Python27\Python27.exe
시작 디렉터리:C:\Python27
인수: c:\WinService.화이
3 - services.msc에서 작성된 서비스를 확인합니다.
스크립트 방식(GUI 없음)
이것은 서비스가 일괄 처리나 설치 스크립트 등 사용자가 제어할 수 없는 자동화된 비인터랙티브 절차에 포함되어 있는 경우에 편리합니다.명령어는 관리자 권한으로 실행되는 것으로 간주됩니다.
이 를 참조하는 됩니다.nssm.exe
할 때는, 풀 , 풀 패스, 풀 패스, 풀 패스, 풀 패스라고 하는 것을 하는 것을 c:\path\to\nssm.exe
시스템이 인식하지 못하는 개인 경로에 위치할 수 있는 자체 포함 실행 파일이기 때문입니다.
1. 서비스 설치
서비스 이름, 적절한 Python 실행 파일의 경로 및 스크립트의 경로를 지정해야 합니다.
nssm.exe install ProjectService "c:\path\to\python.exe" "c:\path\to\project\app\main.py"
좀 더 명확하게:
nssm.exe install ProjectService
nssm.exe set ProjectService Application "c:\path\to\python.exe"
nssm.exe set ProjectService AppParameters "c:\path\to\project\app\main.py"
또는 Python 앱을 Python 모듈로 시작할 수도 있습니다.명령어 셸에서 시작할 때처럼 nssm에게 적절한 시작 디렉토리로 변경해야 함을 알리는 간단한 방법이 있습니다.
nssm.exe install ProjectService "c:\path\to\python.exe" "-m app.main"
nssm.exe set ProjectService AppDirectory "c:\path\to\project"
이 접근 방식은 가상 환경 및 자체 포함(내장) Python 설치에서 잘 작동합니다.이러한 환경에서 일반적인 방법으로 경로 문제를 올바르게 해결했는지 확인하십시오.nssm은 필요에 따라 환경변수(예: PYTONPATH)를 설정할 수 있으며 배치 스크립트를 실행할 수도 있습니다.
2. 서비스를 시작합니다.
nssm.exe start ProjectService
3. 서비스를 정지한다.
nssm.exe stop ProjectService
4. 서비스를 삭제하려면confirm
매개 변수를 눌러 대화형 확인을 건너뜁니다.
nssm.exe remove ProjectService confirm
저는 몇 주 전에 선택된 답변을 상향 조정했지만, 그 사이에 이 주제에 대해 훨씬 더 많은 어려움을 겪었습니다.특별한 Python을 설치하고 특수 모듈을 사용하여 스크립트를 서비스로 실행하는 것은 단순히 잘못된 방법이라고 생각합니다.휴대성 등은 어떻습니까?
흡인하지 않는 훌륭한 Service Manager를 우연히 알게 되었습니다.이 덕분에 Windows Services를 쉽게 다룰 수 있게 되었습니다.설치된 서비스에 옵션을 전달할 수 있기 때문에 Python 실행 파일을 선택하고 스크립트를 옵션으로 전달할 수 있습니다.
저는 아직 이 솔루션을 시도하지 않았습니다만, 지금 바로 시도하여 이 게시물을 업데이트하겠습니다.또한 Windows에서 Virtualenvs를 사용하는 데 관심이 있기 때문에 조만간 튜토리얼을 작성하여 여기에 링크할 수도 있습니다.
가장 간단한 방법은 네이티브명령어 sc.exe를 사용하는 것입니다.
sc create PythonApp binPath= "C:\Python34\Python.exe --C:\tmp\pythonscript.py"
참고 자료:
- https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
- sc.exe를 사용하여 서비스를 작성할 때 컨텍스트 매개 변수를 전달하려면 어떻게 해야 합니까?
거의 모든 Windows 실행 파일을 서비스로 설치하는 방법에는 몇 가지 대안이 있습니다.
방법 1: rktools의 instsrv 및 srvany를 사용합니다.실행
Windows Home Server 또는 Windows Server 2003(WinXP에서도 사용 가능)의 경우 Windows Server 2003 자원 키트툴에는 instsrv.exe 및 srvany.exe라는 유틸리티가 함께 제공됩니다.이러한 유틸리티를 사용하는 방법에 대한 자세한 내용은 Microsoft KB 문서KB137890 을 참조해 주세요.
Windows Home Server 에서는, 이러한 유틸리티에 적절한 「Any Service Installer」라고 하는 편리한 래퍼가 준비되어 있습니다.
방법 2: Windows NT에서 ServiceInstaller를 사용합니다.
Windows NT용 ServiceInstaller(여기에서 다운로드 가능)를 사용하여 python 명령을 사용할 수 있는 다른 방법이 있습니다.이름과는 달리 Windows 2000과 Windows XP에서도 사용할 수 있습니다.다음은 python 스크립트를 서비스로 설치하는 방법에 대한 몇 가지 지침입니다.
Python 스크립트 설치
ServiceInstaller를 실행하여 새 서비스를 만듭니다.(이 예에서는 python이 c:\python25에 설치되어 있는 것을 전제로 하고 있습니다).
Service Name : PythonTest Display Name : PythonTest Startup : Manual (or whatever you like) Dependencies : (Leave blank or fill to fit your needs) Executable : c:\python25\python.exe Arguments : c:\path_to_your_python_script\test.py Working Directory : c:\path_to_your_python_script
설치 후 제어판의 서비스 애플릿을 열고 PythonTest 서비스를 선택하고 시작합니다.
첫 번째 답변 후 SO에 이미 관련된 Q&A가 올라오고 있는 것을 알게 되었습니다.다음 항목도 참조하십시오.
(Windows에서) Python 스크립트를 서비스로 실행할 수 있습니까?어떻게?
Python으로 작성한 서비스를 Windows에서 인식하려면 어떻게 해야 합니까?
동작 방법에 대해 단계별로 설명합니다.
1- 먼저 위에서 설명한 기본 골격에 따라 python 파일을 만듭니다.또한 "c:\PythonFiles\AppServerSvc.py"와 같은 경로에 저장합니다.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service \n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down \n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - 이 단계에서 서비스를 등록해야 합니다.
관리자 권한으로 명령 프롬프트를 실행하고 다음과 같이 입력합니다.
sc create TestService binpath= "C:Python36 Pythonexe c:\PythonFiles\AppServerSvc.py" DisplayName= "TestService" start= auto
binpath의 첫 번째 인수는 python의 경로입니다.실행
binpath의 두 번째 인수는 이미 작성한 python 파일의 경로입니다.
"=" 기호마다 한 칸씩 넣어야 한다는 것을 잊지 마세요.
그럼 모든 게 괜찮다면, 네가 봐야지.
[SC] Create Service SUCCESS
이제 python 서비스가 Windows 서비스로 설치됩니다.Service Manager 및 레지스트리에서 확인할 수 있습니다.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\테스트 서비스
3-알겠습니다.Service Manager에서 서비스를 시작할 수 있습니다.
이 서비스 골격을 제공하는 모든 python 파일을 실행할 수 있습니다.
pysc: Python 서비스 컨트롤 매니저
pythonhosted.org 에서 서비스로 실행하는 스크립트의 예:
from xmlrpc.server import SimpleXMLRPCServer from pysc import event_stop class TestServer: def echo(self, msg): return msg if __name__ == '__main__': server = SimpleXMLRPCServer(('127.0.0.1', 9001)) @event_stop def stop(): server.server_close() server.register_instance(TestServer()) server.serve_forever()
서비스 생성 및 시작
import os import sys from xmlrpc.client import ServerProxy import pysc if __name__ == '__main__': service_name = 'test_xmlrpc_server' script_path = os.path.join( os.path.dirname(__file__), 'xmlrpc_server.py' ) pysc.create( service_name=service_name, cmd=[sys.executable, script_path] ) pysc.start(service_name) client = ServerProxy('http://127.0.0.1:9001') print(client.echo('test scm'))
서비스 중지 및 삭제
import pysc service_name = 'test_xmlrpc_server' pysc.stop(service_name) pysc.delete(service_name)
pip install pysc
python 3+의 nssm
(py 파일을 pyinstaller로 .exe로 변환했습니다)
nssm: 앞서 설명한 바와 같이
- nssm install {ServiceName} 실행
NSSM 콘솔:
path: 프로그램에 대한 경로.실행
스타트업 디렉토리: path\to\your\# 경로와 동일하지만 프로그램이 없습니다.실행
인수: 비어 있습니다.
프로젝트를 .exe로 변환하지 않을 경우
- 파일을 .
python {{your python.py file name}}
- .bat 파일의 경로를 설정합니다.
저는 pywin32로 서비스로 호스팅을 시작했습니다.
문제없지만 시스템 부팅 시 30초 이내에 서비스를 시작할 수 없다는 문제가 발생하였습니다(Windows의 경우 기본 타임아웃).윈도우즈 부팅이 하나의 물리적 시스템에서 호스트되는 여러 가상 시스템에서 동시에 수행되고 IO 로드가 매우 컸기 때문에 이 작업은 매우 중요했습니다.오류 메시지:
Error 1053: The service did not respond to the start or control request in a timely fashion.
Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.
저는 pywin과 많이 싸웠지만, 이 답변에 제시된 대로 NSSM을 사용하게 되었습니다.그곳으로 이동하는 것은 매우 쉬웠다.
루프 또는 서브스레드를 사용한 완전한 pywin32 예시
며칠 동안 이 작업을 반복한 후, pywin32를 사용하여 멋지고 자제된 상태를 유지하는 것이 제가 찾고 싶었던 답변입니다.
이것은 1개의 루프베이스 솔루션과1개의 스레드베이스 솔루션의 완전한 동작 코드입니다.python 2와 3 모두에서 동작할 수 있지만, 저는 2.7과 Win7에서 최신 버전만 테스트했습니다.루프는 코드 폴링에 적합해야 하며 트레드는 서버와 같은 코드로 동작해야 합니다.정상적으로 셧다운할 수 있는 표준적인 방법이 없는 웨이트리스 wsgi 서버에서는 정상적으로 동작하는 것 같습니다.
그리고 이런 예는 많은 것 같습니다.거의 도움이 되지만실제로는 오해의 소지가 있는 것 같습니다.다른 예는 맹목적으로 오려 붙이고 있기 때문입니다.내가 틀릴 수도 있는데 왜 이벤트를 만들죠?
그것은 특히 스레드 버전의 출구가 얼마나 깨끗한지에 대해 제가 아직 다소 불안한 입장에 있다고 생각한다는 것을 의미하지만, 적어도 여기에서는 오해를 불러일으킬 만한 것은 없다고 생각합니다.
실행하려면 코드를 파일에 복사하고 지침을 따르십시오.
업데이트:
단순 플래그를 사용하여 스레드를 종료합니다.'이렇게 하다'
비협조적인 서버 스레드를 종료하는 보다 상세한 예에 대해서는, 웨이트리스 wsgi 서버에 관한 제 투고를 참조해 주세요.
# uncomment mainthread() or mainloop() call below
# run without parameters to see HandleCommandLine options
# install service with "install" and remove with "remove"
# run with "debug" to see print statements
# with "start" and "stop" watch for files to appear
# check Windows EventViever for log messages
import socket
import sys
import threading
import time
from random import randint
from os import path
import servicemanager
import win32event
import win32service
import win32serviceutil
# see http://timgolden.me.uk/pywin32-docs/contents.html for details
def dummytask_once(msg='once'):
fn = path.join(path.dirname(__file__),
'%s_%s.txt' % (msg, randint(1, 10000)))
with open(fn, 'w') as fh:
print(fn)
fh.write('')
def dummytask_loop():
global do_run
while do_run:
dummytask_once(msg='loop')
time.sleep(3)
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global do_run
do_run = True
print('thread start\n')
dummytask_loop()
print('thread done\n')
def exit(self):
global do_run
do_run = False
class SMWinservice(win32serviceutil.ServiceFramework):
_svc_name_ = 'PyWinSvc'
_svc_display_name_ = 'Python Windows Service'
_svc_description_ = 'An example of a windows service in Python'
@classmethod
def parse_command_line(cls):
win32serviceutil.HandleCommandLine(cls)
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stopEvt = win32event.CreateEvent(None, 0, 0, None) # create generic event
socket.setdefaulttimeout(60)
def SvcStop(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.stopEvt) # raise event
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
# UNCOMMENT ONE OF THESE
# self.mainthread()
# self.mainloop()
# Wait for stopEvt indefinitely after starting thread.
def mainthread(self):
print('main start')
self.server = MyThread()
self.server.start()
print('wait for win32event')
win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)
self.server.exit()
print('wait for thread')
self.server.join()
print('main done')
# Wait for stopEvt event in loop.
def mainloop(self):
print('loop start')
rc = None
while rc != win32event.WAIT_OBJECT_0:
dummytask_once()
rc = win32event.WaitForSingleObject(self.stopEvt, 3000)
print('loop done')
if __name__ == '__main__':
SMWinservice.parse_command_line()
「」를 사용해 과 같습니다.win32serviceutil
동작하지만 복잡하며 디버깅과 변경을 어렵게 합니다.NSSM(Non-Seeking Service Manager)을 사용하는 것이 훨씬 쉽습니다.일반 python 프로그램을 작성하고 쉽게 디버깅할 수 있으며, 최종적으로 동작하면 NSSM을 사용하여 1분 이내에 서비스로 설치할 수 있습니다.
admin) 에서 "()"을 실행합니다.nssm.exe install NameOfYourService
다음 옵션을 입력합니다.
- path: (python.exe 경로 등)
C:\Python27\Python.exe
) - Arguments: (python 스크립트의 경로 등)
c:\path\to\program.py
)
덧붙여서, 프로그램이 로그 파일에 보관하고 싶은 유용한 메시지를 인쇄하는 경우, NSSM은 이것과 더 많은 것을 처리할 수 있습니다.
이 답변은 Stack Overflow의 여러 소스로부터의 표절입니다.대부분 위의 소스입니다만, 다른 소스를 잊어버렸습니다.죄송합니다.단순하고 스크립트는 "있는 그대로"테스트하는 릴리스의 경우 스크립트를 작성한 후 서버에 복사하고 관련 서비스를 Stop/Start합니다.또한 모든 스크립트 언어(Python, Perl, node.js)와 GitBash, PowerShell 등의 배치 스크립트, 오래된 DOS bat 스크립트에서도 사용할 수 있습니다.pyGlue는 Windows 서비스와 스크립트 사이에 있는 접착제입니다.
'''
A script to create a Windows Service, which, when started, will run an executable with the specified parameters.
Optionally, you can also specify a startup directory
To use this script you MUST define (in class Service)
1. A name for your service (short - preferably no spaces)
2. A display name for your service (the name visibile in Windows Services)
3. A description for your service (long details visible when you inspect the service in Windows Services)
4. The full path of the executable (usually C:/Python38/python.exe or C:WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe
5. The script which Python or PowerShell will run(or specify None if your executable is standalone - in which case you don't need pyGlue)
6. The startup directory (or specify None)
7. Any parameters for your script (or for your executable if you have no script)
NOTE: This does not make a portable script.
The associated '_svc_name.exe' in the dist folder will only work if the executable,
(and any optional startup directory) actually exist in those locations on the target system
Usage: 'pyGlue.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
Options for 'install' and 'update' commands only:
--username domain\\username : The Username the service is to run under
--password password : The password for the username
--startup [manual|auto|disabled|delayed] : How the service starts, default = manual
--interactive : Allow the service to interact with the desktop.
--perfmonini file: .ini file to use for registering performance monitor data
--perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll
Options for 'start' and 'stop' commands only:
--wait seconds: Wait for the service to actually start or stop.
If you specify --wait with the 'stop' option, the service and all dependent services will be stopped,
each waiting the specified period.
'''
# Import all the modules that make life easy
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
import win32evtlogutil
import os
from logging import Formatter, Handler
import logging
import subprocess
# Define the win32api class
class Service (win32serviceutil.ServiceFramework):
# The following variable are edited by the build.sh script
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
_svc_description_ = "Test Running Python Scripts as a Service"
service_exe = 'c:/Python27/python.exe'
service_script = None
service_params = []
service_startDir = None
# Initialize the service
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.configure_logging()
socket.setdefaulttimeout(60)
# Configure logging to the WINDOWS Event logs
def configure_logging(self):
self.formatter = Formatter('%(message)s')
self.handler = logHandler()
self.handler.setFormatter(self.formatter)
self.logger = logging.getLogger()
self.logger.addHandler(self.handler)
self.logger.setLevel(logging.INFO)
# Stop the service
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
# Run the service
def SvcDoRun(self):
self.main()
# This is the service
def main(self):
# Log that we are starting
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
# Fire off the real process that does the real work
logging.info('%s - about to call Popen() to run %s %s %s', self._svc_name_, self.service_exe, self.service_script, self.service_params)
self.process = subprocess.Popen([self.service_exe, self.service_script] + self.service_params, shell=False, cwd=self.service_startDir)
logging.info('%s - started process %d', self._svc_name_, self.process.pid)
# Wait until WINDOWS kills us - retrigger the wait for stop every 60 seconds
rc = None
while rc != win32event.WAIT_OBJECT_0:
rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))
# Shut down the real process and exit
logging.info('%s - is terminating process %d', self._svc_name_, self.process.pid)
self.process.terminate()
logging.info('%s - is exiting', self._svc_name_)
class logHandler(Handler):
'''
Emit a log record to the WINDOWS Event log
'''
def emit(self, record):
servicemanager.LogInfoMsg(record.getMessage())
# The main code
if __name__ == '__main__':
'''
Create a Windows Service, which, when started, will run an executable with the specified parameters.
'''
# Check that configuration contains valid values just in case this service has accidentally
# been moved to a server where things are in different places
if not os.path.isfile(Service.service_exe):
print('Executable file({!s}) does not exist'.format(Service.service_exe), file=sys.stderr)
sys.exit(0)
if not os.access(Service.service_exe, os.X_OK):
print('Executable file({!s}) is not executable'.format(Service.service_exe), file=sys.stderr)
sys.exit(0)
# Check that any optional startup directory exists
if (Service.service_startDir is not None) and (not os.path.isdir(Service.service_startDir)):
print('Start up directory({!s}) does not exist'.format(Service.service_startDir), file=sys.stderr)
sys.exit(0)
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(Service)
servicemanager.StartServiceCtrlDispatcher()
else:
# install/update/remove/start/stop/restart or debug the service
# One of those command line options must be specified
win32serviceutil.HandleCommandLine(Service)
이제 약간의 편집이 있어 'pyGlue'라는 이름의 모든 서비스를 원하지 않습니다.스크립트(빌드)가 있습니다.sh) 비트를 꽂고 커스터마이즈된 'pyGlue'를 만들고 '.exe'를 만듭니다.이 '.exe'는 Windows 서비스로 설치됩니다.설치가 완료되면 자동으로 실행되도록 설정할 수 있습니다.
#!/bin/sh
# This script build a Windows Service that will install/start/stop/remove a service that runs a script
# That is, executes Python to run a Python script, or PowerShell to run a PowerShell script, etc
if [ $# -lt 6 ]; then
echo "Usage: build.sh Name Display Description Executable Script StartupDir [Params]..."
exit 0
fi
name=$1
display=$2
desc=$3
exe=$4
script=$5
startDir=$6
shift; shift; shift; shift; shift; shift
params=
while [ $# -gt 0 ]; do
if [ "${params}" != "" ]; then
params="${params}, "
fi
params="${params}'$1'"
shift
done
cat pyGlue.py | sed -e "s/pyGlue/${name}/g" | \
sed -e "/_svc_name_ =/s?=.*?= '${name}'?" | \
sed -e "/_svc_display_name_ =/s?=.*?= '${display}'?" | \
sed -e "/_svc_description_ =/s?=.*?= '${desc}'?" | \
sed -e "/service_exe =/s?=.*?= '$exe'?" | \
sed -e "/service_script =/s?=.*?= '$script'?" | \
sed -e "/service_params =/s?=.*?= [${params}]?" | \
sed -e "/service_startDir =/s?=.*?= '${startDir}'?" > ${name}.py
cxfreeze ${name}.py --include-modules=win32timezone
설치 - 서버와 스크립트를 지정된 폴더에 복사합니다.'install' 옵션을 사용하여 '.exe'를 Administrator로 실행합니다.Windows 서비스를 Administrator로 열고 서비스를 시작합니다.업그레이드하려면 스크립트의 새 버전을 복사하고 서비스를 중지/시작하기만 하면 됩니다.
이제 모든 서버가 다릅니다. Python 설치와 폴더 구조가 다릅니다.모든 서버의 폴더를 build.sh 및 build.sh 복사본으로 유지합니다.그리고 서버상의 모든 서비스를 재구축하기 위한 'serverBuild.sh' 스크립트를 만듭니다.
# A script to build all the script based Services on this PC
sh build.sh AutoCode 'AutoCode Medical Documents' 'Autocode Medical Documents to SNOMED_CT and AIHW codes' C:/Python38/python.exe autocode.py C:/Users/russell/Documents/autocoding -S -T
이것은 원래의 질문에 대한 답변은 아니지만, Windows 부팅 시 Python 스크립트를 자동으로 시작하려는 다른 사용자에게 도움이 될 수 있습니다.Windows 태스크스케줄러를 참조해 주세요.Windows Service의 모든 서비스 기능을 사용하지 않고 부팅 후 스크립트를 시작하는 것이 훨씬 쉽습니다.
새 작업을 만들고 트리거로 "시작 시"를 선택하고 "C:"를 사용하여 "프로그램 시작"을 선택합니다.\Python39\python.exe"는 프로그램(또는 python.exe가 있는 곳) 및 스크립트("C:...")의 풀 경로로 사용됩니다.인수(경로에 공백이 포함되어 있는 경우 "를 사용할 수 있습니다).스크립트의 경로를 선택할 수도 있습니다(예: "C:..."와 같이 .py 파일이 없는 경우).\my_discripts")는 스크립트에서 상대 경로를 사용하는 경우(예를 들어 로깅에 사용)에 대해 "시작"을 나타냅니다.
https://www.chrisumbel.com/article/windows_services_in_python
PySvc.py에 팔로업 합니다.
dll 폴더 변경
이게 오래됐다는 건 알지만 난 이걸 영원히 간직하고 있었어.이 문제는 이 파일을 복사함으로써 해결되었습니다.pywintypes36.dll
-> Python36\Lib\site-packages\pywin32_system32에서
To -> Python36\Lib\site-packages\win32
setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
- python 폴더의 경로 변경 방법
cd C:\Users\user\AppData\Local\Programs\Python\Python38-32
NET START PySvc
NET STOP PySvc
언급URL : https://stackoverflow.com/questions/32404/how-do-you-run-a-python-script-as-a-service-in-windows
'programing' 카테고리의 다른 글
Laravel 메일: 보기 대신 문자열 전달 (0) | 2022.09.25 |
---|---|
타이프스크립트 내보내기 vs. 기본 내보내기 (0) | 2022.09.25 |
Jackson & message - Json Mapping Exception - START_ARray 토큰이 아닌 것으로 역직렬화할 수 없음 (0) | 2022.09.25 |
Java에서 목록으로 맵을 변환하는 방법 (0) | 2022.08.31 |
vue.js axios POST에서 Laravel로 JSON을 입수하려면 어떻게 해야 합니까? (0) | 2022.08.31 |