【发布时间】:2011-04-12 11:53:38
【问题描述】:
我使用以下代码创建了一个windwos服务:
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time
class aservice(win32serviceutil.ServiceFramework):
_svc_name_ = "PAStoDistillerIFC"
_svc_display_name_ = "PAS DW to Distiller Interface"
_svc_description_ = "Service that checks the Clinical Research folder for any new files from PAS to process in Distiller"
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):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
#self.timeout = 640000 #640 seconds / 10 minutes (value is in milliseconds)
self.timeout = 120000 #120 seconds / 2 minutes
# This is how long the service will wait to run / refresh itself (see script below)
while 1:
# Wait for service stop signal, if timeout, loop again
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# Check to see if self.hWaitStop happened
if rc == win32event.WAIT_OBJECT_0:
# Stop signal encountered
servicemanager.LogInfoMsg("PAStoDistillerIFC - STOPPED!") #For Event Log
break
else:
#[actual service code between rests]
try:
file_path = "D:\\SCRIPTS\\script.py"
execfile(file_path) #Execute the script
except:
servicemanager.LogInfoMsg("File CRASHED")
pass
#[actual service code between rests]
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(aservice)
要运行这个脚本:
import os, re, urllib, urllib2, time, datetime
def postXML( path, fname):
fileresultop = open("D:\\CLinicalResearch\\SCRIPTS\\LOG.txt", 'a') # open result file
fileresultop.write('CheckXXX ')
fileresultop.close()
now = datetime.datetime.now() #####ALWAYS CRASHES HERE######
fileresult = open("D:\\SCRIPTS\\IFCPYTHONLOG.txt", 'a') # open result file
fileresultop = open("D:\\SCRIPTS\\LOG.txt", 'a')
fileresultop.write('Check2 ')
fileresultop.close()
path="D:\\Test2" # Put location of XML files here.
procpath="D:\\Test2Processed" # Location of processed files
now = datetime.datetime.now()
dirList=os.listdir(path)
for fname in dirList: # For each file in directory
if re.search("PatientIndexInsert", fname): # Brand new patient records
fileresultop = open("D:\\SCRIPTS\\LOG.txt", 'a') # open result file
fileresultop.write('Check1 ')
fileresultop.close()
postXML(path, fname)
我已将脚本缩减为我认为会崩溃的裸代码。
这可以从命令行完美运行,我在自己的登录名下运行 Windows 服务。 一旦我将 datetime 函数从函数中取出,它似乎就可以工作了。
编辑 1: 我看到服务在空白环境中运行。我自己没有设置任何环境变量。
编辑 2: 添加回溯:
File "D:\ClinicalResearch\SCRIPTS\PAS2DIST.py", line 23, in <module>
postXML(path, fname)
File "D:\ClinicalResearch\SCRIPTS\PAS2DIST.py", line 6, in postXML
now = datetime.datetime.now()
NameError: global name 'datetime' is not defined
【问题讨论】:
-
你有崩溃的回溯吗?您可以使用
traceback模块将其作为字符串获取,以便在需要时对其进行记录。 -
如果它在日期时间崩溃,我认为它与配置文件的区域设置有关(或者在作为服务运行时缺少上述设置)。在C++中会有
CreateProcessAsUser,也许python也有类似的功能。 -
如果您在代码开头导入 win32traceutil,您可以使用 win32traceutil.py(我安装的 C:\Python27\Lib\site-packages\win32\lib)在运行时监控输出一项服务。这应该可以让您更好地看到错误。
-
您可能应该将
servicemanager.LogInfoMsg("File CRASHED")从 info 更改为 error 并在消息中包含堆栈回溯。这样,您应该获得足够的信息以在事件日志中找到问题以及任何未来的问题。 -
谢谢大家,我尝试使用打印异常:除了:servicemanager.LogErrorMsg(traceback.print_exc(file=sys.stdout)) 但具有讽刺意味的是它给了我一个错误:文件“D:\ClinicalResearch\ SCRIPTS\Script1.py",第 49 行,在 SvcDoRun servicemanager.LogErrorMsg(traceback.print_exc(file=sys.stdout)) TypeError: None is not a valid string in this context %2: %3