免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4277 | 回复: 2

【已解决】win服务模式下,__import__的问题 [复制链接]

论坛徽章:
0
发表于 2013-09-11 19:34 |显示全部楼层
本帖最后由 wfnh 于 2013-09-13 09:39 编辑

有2个脚本,一个是服务框架,一个是逻辑脚本,调试逻辑脚本或者是直接运行逻辑脚本是正常的,__import__也没问题,但如果是用服务的形式启动,就import不了···很奇怪,求破,代码如下:
  1. import win32serviceutil
  2. import win32service
  3. import win32event
  4. import time

  5. import EventDispatch
  6. from common.util import get_logger

  7. class MonitorService(win32serviceutil.ServiceFramework):
  8.     """
  9.     Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
  10.     Options for 'install' and 'update' commands only:
  11.      --username domain\username : The Username the service is to run under
  12.      --password password : The password for the username
  13.      --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
  14.      --interactive : Allow the service to interact with the desktop.
  15.      --perfmonini file: .ini file to use for registering performance monitor data
  16.      --perfmondll file: .dll file to use when querying the service for
  17.        performance data, default = perfmondata.dll
  18.     Options for 'start' and 'stop' commands only:
  19.      --wait seconds: Wait for the service to actually start or stop.
  20.                      If you specify --wait with the 'stop' option, the service
  21.                      and all dependent services will be stopped, each waiting
  22.                      the specified period.
  23.     """
  24.     #服务名
  25.     _svc_name_ = "MonitorService"
  26.     #服务显示名称
  27.     _svc_display_name_ = "MonitorService"
  28.     #服务描述
  29.     _svc_description_ = u"监控服务"

  30.     def __init__(self, args):
  31.         win32serviceutil.ServiceFramework.__init__(self, args)
  32.         self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
  33.         self.logger = get_logger('service')
  34.         self.manager = EventDispatch.EventDispatch()
  35.         self.isAlive = True

  36.     def SvcDoRun(self):
  37.         self.logger.info("MonitorService running....")
  38.         self.manager.add_all()
  39.         # 等待服务被停止
  40.         win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

  41.     def SvcStop(self):
  42.         # 先告诉SCM停止这个过程
  43.         self.logger.info("MonitorService stopped....")
  44.         self.manager.stop()
  45.         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
  46.         # 设置事件
  47.         win32event.SetEvent(self.hWaitStop)
  48.         self.isAlive = False

  49. if __name__=='__main__':
  50.     win32serviceutil.HandleCommandLine(MonitorService)
复制代码
add_all函数:
  1.     def add_all(self):
  2.         import inspect
  3.         logger = get_logger('EventDispatch')
  4.         #--获得当前文件和当前文件所在的目录
  5.         this_file = inspect.getfile(inspect.currentframe())
  6.         this_dir = os.path.abspath(os.path.dirname(this_file))
  7.         path = os.path.join(this_dir,'customEvent')
  8.         class_list = import_all_module(path,'event.customEvent','evt_*.py')
  9.         if class_list:
  10.             self.event_queue = class_list
  11.         logger.info('EventDispatch_add_all end')
复制代码
import_all_module函数(问题就在这个函数里边):
  1. def import_all_module(path,import_from,pattern = '*.py'):
  2.     '''
  3.     导入路径下的所有模块,返回模块列表,pattern参数可过滤不需要的模块
  4.     '''
  5.     import_logger = get_logger('import')
  6.     if os.path.isdir(path) and os.path.exists(path):
  7.         pattern = os.path.join(path,pattern)
  8.     else:
  9.         return []
  10.     mod_name = []
  11.     class_objs = []
  12.     import_logger.info(pattern)
  13.     for module_file in glob.glob(pattern):
  14.         import_logger.info(module_file)
  15.         module_name,ext = os.path.splitext(os.path.basename(module_file))
  16.         mod_name.append(module_name)
  17.     try:
  18.         modules = __import__(import_from,globals(),locals(),mod_name)  #--问题就在这里
  19.         import_logger.info('------------------')  #--上面出问题后,这里不会走到,并且也不会触发异常···不是很明白
  20.     except:
  21.         import_logger.info('ImportError,mod_name is ',mod_name)
  22.         print 'ImportError,mod_name is ',mod_name
  23.     import_logger.info('mod_name:%s'%(mod_name))
  24.     for mod in mod_name:
  25.         import_logger.info('for mod:%s'%(mod))
  26.         obj = getattr(modules,mod)
  27.         #--循环取到类对象为止
  28.         while(obj):
  29.             if isinstance(obj,types.ModuleType):   #--检查是否为模块类型
  30.                 obj = getattr(obj,mod)
  31.                 import_logger.info('while,continue:%s'%(obj))
  32.                 continue
  33.             elif isinstance(obj,types.TypeType): #--如果是类对象的话,就是目标了
  34.                 class_objs.append(obj)
  35.                 import_logger.info('found class:%s'%(obj))
  36.                 break
  37.     return class_objs
复制代码
如果是单独运行EventDispatch.EventDispatch().add_all()是没问题的····看了一下log····导入的路径也算正常···求破

附上报错的信息:
  1.   File "D:\test-area\getItem\ghs\sf\monitorService\event\eventDispatch.py", line 43, in add_all
  2.     class_list = import_all_module(path,'event.customEvent','evt_*.py')
  3.   File "D:\test-area\getItem\ghs\sf\monitorService\common\util.py", line 51, in import_all_module
  4.     obj = getattr(modules,mod)
  5. UnboundLocalError: local variable 'modules' referenced before assignment
复制代码

论坛徽章:
0
发表于 2013-09-13 09:41 |显示全部楼层
服务模式下··和纯脚本的形式,sys.path的路径是不同的,所以有些第三方库没include进来,导致内部的一些依赖不全,import失败,但我奇怪的是except:  这样居然捕获不了错误,要except Exception,e:才可以

论坛徽章:
2
酉鸡
日期:2014-02-19 09:11:08摩羯座
日期:2014-05-23 10:16:16
发表于 2013-09-13 10:02 |显示全部楼层
所以不能偷懒啊,要用正规except Exception的写法啊:wink: 回复 2# wfnh


   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP