简体   繁体   English

从命令行运行时,Python脚本有效,但从Windows Service运行时,则无效

[英]Python Script works when run from command line but not when run from windows service

I have created a windwos service utilising the following code: 我使用以下代码创建了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)

To run this script: 要运行此脚本:

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)

I have pared down the script to the bare code where I believe this is crashing. 我已经将脚本缩减为裸机代码,我相信这会崩溃。

This works perfectly from the command line, I run the windows service under my own login. 从命令行可以完美运行,我以自己的登录名运行Windows服务。 Once I take the datetime function out of the function it seems to work. 一旦我从该功能中取出datetime函数,它似乎就可以工作了。

Edit 1: I saw that the service runs in a blank environment. 编辑1:我看到该服务在空白环境中运行。 I don't have any environmental variables set myself. 我自己没有设置任何环境变量。

Edit 2: Added traceback: 编辑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

I didn't find the cause but I did find a workaround. 我没有找到原因,但确实找到了解决方法。

I needed to import all the same libraries into the function too. 我也需要将所有相同的库导入该函数。 Once I did that, worked like a charm. 一旦我做到了,就像一个魅力。

Hope this can help someone else. 希望这可以帮助其他人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我从 IDLE 运行但不在命令行中运行时,Python 脚本有效吗? - Python script works when I run from IDLE but not in command line? 从C#运行py脚本但从Windows命令行运行时,“没有名为fcntl的模块” - “No module named fcntl” when py script run from c# but works from windows command line Python 脚本在 Sublime Text 中运行时不起作用,但在命令行中运行 - Python script doesn't work when run in Sublime Text, but works from command line 从命令行 python 脚本运行时 tkinter 不工作 - tkinter not working when run from command line python script 从命令行运行 python 脚本时未找到模块错误 - module not found error when python script is run from command line 从命令行运行 python 脚本时找不到模块 - module not found when python script run from command line Apache2 python脚本在命令行中运行时有效,但在Web浏览器中运行时无效 - Apache2 python script works when run in command line but not when run in web browser 如何从python脚本运行windows命令行? - How to run windows command line from python script? 当命令带有双引号时如何从python运行Windows命令行命令 - How to run a windows command line command from python when the command has double quotes 从Windows命令行运行脚本时,由于“ SQL语句正在进行”,Python sqlite3无法回滚事务。 - Python sqlite3 cannot rollback transaction due to 'SQL statements in progress' when script run from Windows command line.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM