Python脚本在命令行正常,但在Windows服务中不行

1 投票
1 回答
1339 浏览
提问于 2025-04-16 15:34

我创建了一个Windows服务,使用了以下代码:

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服务的。

一旦我把日期时间的功能去掉,似乎就能正常工作了。

编辑 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

1 个回答

0

我没有找到问题的原因,但我找到了一种解决办法。

我发现需要在函数里也导入所有相同的库。这样做之后,一切都正常了。

希望这能帮助到其他人。

撰写回答