【发布时间】:2017-06-20 03:38:07
【问题描述】:
我正在编写一个多进程的 Windows 服务,但我遇到了池中调用的方法的问题。
现在我可以安装并运行该服务,它将The service started running... 输出到日志文件中,但没有别的。
查看进程资源管理器(见下面的屏幕截图),我看到进程正在不断创建和完成,但 TestMethod 中的代码没有运行,服务没有退出池,因为没有别的了正在写入文件。
我无法停止该服务,因为它卡在池中并且没有到达停止事件的检查。
为什么 TestMethod 中的代码根本没有运行?
服务代码:
import servicemanager
import win32event
import win32service
import win32serviceutil
import multiprocessing
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def testMethod(self, testVar):
with open('C:\\Test.log', 'a') as f:
f.write('The method is running: ' + testVar)
f.close()
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):
with open('C:\\Test.log', 'a') as f:
f.write('The service started running...\n')
f.close()
rc = None
p = multiprocessing.Pool(5)
p.map(TestService.testMethod, range(1,6))
with open('C:\\Test.log', 'a') as f:
f.write('Finished method...\n')
f.close()
while rc != win32event.WAIT_OBJECT_0:
with open('C:\\Test.log', 'a') as f:
f.write('The service is running...\n')
f.close()
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
with open('C:\\Test.log', 'a') as f:
f.write('StreamCapture service stopped.\n')
f.close()
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
【问题讨论】:
-
p.map(TestService.testMethod, range(1,6))-TestService.testMethod是一个未绑定的方法。在这个p.map调用中没有TestService的实例。你希望什么对象来执行这个方法? -
该方法最初是通过视频流并运行 ffmpeg 并创建日志。我将方法放在类中,因为我认为它可能遇到范围问题,但它仍然遇到相同的问题,该方法很可能在没有 self 的类外部定义,它会遇到与现在相同的问题.
标签: python multiprocessing python-multiprocessing pool