- 論壇徽章:
- 0
|
本帖最后由 wfnh 于 2013-09-13 09:39 編輯
有2個(gè)腳本,一個(gè)是服務(wù)框架,一個(gè)是邏輯腳本,調(diào)試邏輯腳本或者是直接運(yùn)行邏輯腳本是正常的,__import__也沒問題,但如果是用服務(wù)的形式啟動(dòng),就import不了···很奇怪,求破,代碼如下:- import win32serviceutil
- import win32service
- import win32event
- import time
- import EventDispatch
- from common.util import get_logger
- class MonitorService(win32serviceutil.ServiceFramework):
- """
- Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
- Options for 'install' and 'update' commands only:
- --username domain\username : The Username the service is to run under
- --password password : The password for the username
- --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
- --interactive : Allow the service to interact with the desktop.
- --perfmonini file: .ini file to use for registering performance monitor data
- --perfmondll file: .dll file to use when querying the service for
- performance data, default = perfmondata.dll
- Options for 'start' and 'stop' commands only:
- --wait seconds: Wait for the service to actually start or stop.
- If you specify --wait with the 'stop' option, the service
- and all dependent services will be stopped, each waiting
- the specified period.
- """
- #服務(wù)名
- _svc_name_ = "MonitorService"
- #服務(wù)顯示名稱
- _svc_display_name_ = "MonitorService"
- #服務(wù)描述
- _svc_description_ = u"監(jiān)控服務(wù)"
- def __init__(self, args):
- win32serviceutil.ServiceFramework.__init__(self, args)
- self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
- self.logger = get_logger('service')
- self.manager = EventDispatch.EventDispatch()
- self.isAlive = True
- def SvcDoRun(self):
- self.logger.info("MonitorService running....")
- self.manager.add_all()
- # 等待服務(wù)被停止
- win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
- def SvcStop(self):
- # 先告訴SCM停止這個(gè)過程
- self.logger.info("MonitorService stopped....")
- self.manager.stop()
- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
- # 設(shè)置事件
- win32event.SetEvent(self.hWaitStop)
- self.isAlive = False
- if __name__=='__main__':
- win32serviceutil.HandleCommandLine(MonitorService)
復(fù)制代碼 add_all函數(shù):- def add_all(self):
- import inspect
- logger = get_logger('EventDispatch')
- #--獲得當(dāng)前文件和當(dāng)前文件所在的目錄
- this_file = inspect.getfile(inspect.currentframe())
- this_dir = os.path.abspath(os.path.dirname(this_file))
- path = os.path.join(this_dir,'customEvent')
- class_list = import_all_module(path,'event.customEvent','evt_*.py')
- if class_list:
- self.event_queue = class_list
- logger.info('EventDispatch_add_all end')
復(fù)制代碼 import_all_module函數(shù)(問題就在這個(gè)函數(shù)里邊):- def import_all_module(path,import_from,pattern = '*.py'):
- '''
- 導(dǎo)入路徑下的所有模塊,返回模塊列表,pattern參數(shù)可過濾不需要的模塊
- '''
- import_logger = get_logger('import')
- if os.path.isdir(path) and os.path.exists(path):
- pattern = os.path.join(path,pattern)
- else:
- return []
- mod_name = []
- class_objs = []
- import_logger.info(pattern)
- for module_file in glob.glob(pattern):
- import_logger.info(module_file)
- module_name,ext = os.path.splitext(os.path.basename(module_file))
- mod_name.append(module_name)
- try:
- modules = __import__(import_from,globals(),locals(),mod_name) #--問題就在這里
- import_logger.info('------------------') #--上面出問題后,這里不會(huì)走到,并且也不會(huì)觸發(fā)異常···不是很明白
- except:
- import_logger.info('ImportError,mod_name is ',mod_name)
- print 'ImportError,mod_name is ',mod_name
- import_logger.info('mod_name:%s'%(mod_name))
- for mod in mod_name:
- import_logger.info('for mod:%s'%(mod))
- obj = getattr(modules,mod)
- #--循環(huán)取到類對(duì)象為止
- while(obj):
- if isinstance(obj,types.ModuleType): #--檢查是否為模塊類型
- obj = getattr(obj,mod)
- import_logger.info('while,continue:%s'%(obj))
- continue
- elif isinstance(obj,types.TypeType): #--如果是類對(duì)象的話,就是目標(biāo)了
- class_objs.append(obj)
- import_logger.info('found class:%s'%(obj))
- break
- return class_objs
復(fù)制代碼 如果是單獨(dú)運(yùn)行EventDispatch.EventDispatch().add_all()是沒問題的····看了一下log····導(dǎo)入的路徑也算正!ぁぁで笃
附上報(bào)錯(cuò)的信息:- File "D:\test-area\getItem\ghs\sf\monitorService\event\eventDispatch.py", line 43, in add_all
- class_list = import_all_module(path,'event.customEvent','evt_*.py')
- File "D:\test-area\getItem\ghs\sf\monitorService\common\util.py", line 51, in import_all_module
- obj = getattr(modules,mod)
- UnboundLocalError: local variable 'modules' referenced before assignment
復(fù)制代碼 |
|