編集
「...コンピュータの起動は、 が一時停止して再起動し、任意のユーザーインターフェイスを表示しないことができたときにサービスが自動的に起動することができます。」〜Introduction to Windows Service Applications
Windowsサービスが特定のインターフェイスを利用できるように実装が必要になります。
ですから、Pythonの経由のWindows APIにアクセスする必要があります。
あなたはPython Programming On Win32から、example codeを見ることができ、内の第18章サービス(ch18_servicesフォルダ)は、試料(SmallestServiceが含まれています。
# SmallestService.py
#
# A sample demonstrating the smallest possible service written in Python.
import win32serviceutil
import win32service
import win32event
class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "SmallestPythonService"
_svc_display_name_ = "The smallest possible Python Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# And set my event.
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
# We do nothing other than wait to be stopped!
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)
あなたがここにあなたの特定のPython環境のために適切なpywin32ホイールをダウンロードする必要があります: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32
そしてinstallそれを(システムPY)Pythonで書か可能な最小のサービスを実証admin cmdプロンプトから):
> cd \program files\python<ver>\scripts
> pip install \path\to\pywin32‑221‑cp<ver>‑cp<ver>m‑win_<arch>.whl
または(ユーザーあたり、通常のCMDプロンプトから)それをインストール:
> cd \program files\python<ver>\scripts
> pip install --user \path\to\pywin32‑221‑cp<ver>‑cp<ver>m‑win_<arch>.whl
は適切<ver>
と<arch>
の出現箇所を置き換えてください。
ありがとうございました!そして、もし私のサービスが他のスクリプトを実行させたいのであれば、どこでどのようにコードを書かなければなりませんか?私はちょうどwin32serviceutil.HandleCommandLine(SmallestPythonService)の下にsubprocess.call( "script.py")のようなものを置くべきですか? –
SvcDoRun()関数の内部からスクリプトを起動してみてください。 – veganaiZe
私はあなたの答えをそれがうまくいくように受け入れました。サービスがインストールされていて、同じCMDでスクリプトが実行され始めました。私は "python script.py install"コマンドを使用しました。しかし、それは開始されていない、私はそのCMDウィンドウを開いたままにしている限り動作しています。私はこれを取得しています: "インスタンスのSvcRun()メソッドが失敗しました Windowsイベントビューアで<トレースバック取得中にtraceback.print_exception()が失敗しました %2:%3" –