def open_browser(dependency,step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name CommonUtil.ExecLog(sModuleInfo, "Opening browser", 1) sClientName=dependency['Browser'] sTestStepReturnStatus = WebProgram.BrowserSelection(sClientName) print sTestStepReturnStatus return sTestStepReturnStatus
def Generate_TCId(Section_Path, tmp_TC_Id): # Prefix a 3 letter section name to the tc_id try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name TC_ID_Prefix = '' if 'Contacts' in Section_Path: TC_ID_Prefix = 'Con' elif 'Calendar' in Section_Path: TC_ID_Prefix = 'Cal' elif 'Backup' in Section_Path or 'Restore' in Section_Path: TC_ID_Prefix = 'Bak' elif 'Music' in Section_Path: TC_ID_Prefix = 'Mus' elif 'Video' in Section_Path: TC_ID_Prefix = 'Vid' elif 'Picture' in Section_Path: TC_ID_Prefix = 'Pic' elif 'Document' in Section_Path: TC_ID_Prefix = 'Doc' elif 'PIM' in Section_Path: TC_ID_Prefix = 'Pim' elif 'Media' in Section_Path: TC_ID_Prefix = 'Med' elif 'Settings' in Section_Path: TC_ID_Prefix = 'Set' else: TC_ID_Prefix = Section_Path.split('.')[len(Section_Path.split('.')) - 1][:3].upper() TC_Id = "%s-%s" % (TC_ID_Prefix.upper(), str(tmp_TC_Id).lstrip('0').zfill(4)) return TC_Id except Exception, e: print "Exception:", e return tmp_TC_Id
def module_path_gen(root_dir): for root, subdirs, files in os.walk(root_dir): for f in files: path = os.path.join(root, f) info = inspect.getmoduleinfo(path) if info is not None and info.module_type == imp.PY_SOURCE: yield path
def UpdateProcess(self): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: if self.EnableUpdate == False: #print "Framework update check is disabled" CommonUtil.ExecLog(sModuleInfo, "Framework update check is disabled", 4) return False if self.CheckUpdate(): if self.AutoUpdate == False: print "Press 1 to update the Framework or any other key to cancel the update:" UserInput = raw_input() if UserInput == "1": print "Performing Update..." if self.GetUpdate(): return self.Restart() else: return False CommonUtil.ExecLog(sModuleInfo, "Framework update check is disabled", 4) return False else: print "Performing Auto Update to the newest framework" if self.GetUpdate(): return self.Restart() else: #print "No update available" #CommonUtil.ExecLog(sModuleInfo,"No update available",4) return True except Exception, e: print "Exception %s" % e CommonUtil.ExecLog(sModuleInfo, "Exception:%s" % e, 4) return False
def click_button(ElemId=None, ElemPath=None, ElemRole=None, ElemValue=None, ElemPosition=None): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: ElementName = [Key for Key, Value in Global.Ids.items() if Value == ElemId or Value == ElemPath] if ElemPath == None: element = Find_Element(elem_id=ElemId, elem_path=ElemPath, elem_role=ElemRole, elem_value=ElemValue, elem_position=ElemPosition) else: element = [ElemPath] if element != False: if element[0].enabled.get() == True: element[0].click() # print "%s > Button (%s) has been clicked" %(sModuleInfo,ElementName) CommonUtil.ExecLog(sModuleInfo, "Button (%s) has been clicked" % ElementName, 1) return True else: # print "%s > Button (%s) was not enabled" %(sModuleInfo,ElementName) CommonUtil.ExecLog(sModuleInfo, "Button (%s) was not enabled" % ElementName, 1) return False else: # print "%s > Button (%s) was not be found" %(sModuleInfo,ElementName) CommonUtil.ExecLog(sModuleInfo, "Button (%s) was not be found" % ElementName, 1) return False except Exception, e: return CommonUtil.LogCriticalException(sModuleInfo, e)
def compute(): filename = 'numb.py' try: (name, suffix, mode, mtype) = inspect.getmoduleinfo(filename) except TypeError: print 'Could not determine module type of %s' % filename pass
def check_uncheck_box(ElemId=None, ElemPath=None, check_uncheck=None, ElemRole=None, ElemValue=None, ElemPosition=None): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: element = Find_Element(elem_id=ElemId, elem_path=ElemPath, elem_role=ElemRole, elem_value=ElemValue, elem_position=ElemPosition) if element != False and len(element) > 0: status = element[0].value.get() if check_uncheck == 1: if status == 1: return True else: element[0].click() elif check_uncheck == 0: if status == 0: return True else: element[0].click() status = element[0].value.get() if status == check_uncheck: return True else: return False else: return False except Exception, e: return CommonUtil.LogCriticalException(sModuleInfo, e)
def set_txt_value_by_keystroke(id_path, txt): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name #set value with empty string # print "seting the value to empty" # os.system('~/Desktop/MouseTools -leftClick') print "calling set funcion to set the name to empty" set_txt_value(id_path, "") # os.system('~/Desktop/MouseTools -leftClick') #get and click location print "getting clickable location" text_field_locaion_to_click = get_clickable_location(id_path) print "found clicable locaiton" click_given_loc(text_field_locaion_to_click) time.sleep(1) #keystroke the value in print "about to type keystroke" keystroke(txt) print "done keysroking" return True except Exception, e: print "%s > Exception Happened (%s)" % (sModuleInfo, e) CommonUtil.ExecLog(sModuleInfo, "Exception Happened (%s)" % e, 3) return False
def source(self): # == file """ Source file (root + path) of the module. + path@str|None source path or None if no source file available. ? Unknown = unsafe """ srcfile = None if hasattr(self._module, "__file__"): info = inspect.getmoduleinfo(self._module.__file__) if info == None: pass elif info[3] == imp.PY_SOURCE: srcfile = self._module.__file__ elif info[3] == imp.PY_COMPILED: srcfile = self._module.__file__ path, ext = os.path.splitext(srcfile) srcfile = path + ".py" if not os.path.exists(srcfile): srcfile = None elif info[3] == imp.C_EXTENSION: pass elif info[3] == imp.PY_RESOURCE: pass else: raise RuntimeError("should not happen") return srcfile
def exit(error=None): import sys import inspect from termcolor import colored if inspect.stack()[1][3] == '<module>': print "Check file ", inspect.stack()[1][1], "for checkpath in the main code, not in some definition" else: text = "" path_full = inspect.stack()[1][1] path_name = inspect.getmoduleinfo(path_full).name ERROR_GENERAL = "ERROR in Module: " + inspect.stack( )[1][3] + " Skript: " + path_name if error is None: ERROR = ERROR_GENERAL else: ERROR = error + " (" + ERROR_GENERAL + ")" # print "KA:",ERROR.split()[0][0:5] if ERROR.split()[0][0:5] == "ERROR": #text = colored(ERROR, 'red', attrs=['bold']) text = printred("ERROR") else: #text = colored(ERROR, 'blue', attrs=['bold']) text = printred("ERROR") sys.exit(text) sys.exit()
def source(self): # == file """ Source file (root + path) of the module. + path@str|None source path or None if no source file available. ? Unknown = unsafe """ srcfile = None if hasattr(self._module,"__file__"): info = inspect.getmoduleinfo(self._module.__file__) if info == None: pass elif info[3] == imp.PY_SOURCE: srcfile = self._module.__file__ elif info[3] == imp.PY_COMPILED: srcfile = self._module.__file__ path,ext = os.path.splitext(srcfile) srcfile = path + ".py" if not os.path.exists(srcfile): srcfile = None elif info[3] == imp.C_EXTENSION: pass elif info[3] == imp.PY_RESOURCE: pass else: raise RuntimeError("should not happen") return srcfile
def get_elem_with_role(obj_list, role_type): #there is a possiblity of having duplicate element so we need to build our list and send as list and not as obj try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name elem_with_role = [] for temp_obj in obj_list: try: role_name = get_role_of_element(temp_obj) # print "role of element is :" # print role_name # print role_type except: a = 1 if (role_name == role_type): # print "matched" elem_with_role.append(temp_obj) #print elem_with_role else: a = 1 #print "didnt match" #print elem_with_role return elem_with_role except Exception, e: print "%s > Exception Happened (%s)" % (sModuleInfo, e) CommonUtil.ExecLog(sModuleInfo, "Exception Happened (%s)" % e, 3) return False
def Insert_ContainerTypeData(conn, TC_Id, Step_Index, Data_Id_List): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name Container_Data_Id = "%s_s%s" % (TC_Id, Step_Index) for eachDataId in Data_Id_List: if isinstance(eachDataId, tuple): # if its a tuple, then its a edit data of (cur_data_id, new_data_id) result = DBUtil.InsertNewRecordInToTable(conn, "container_type_data", dataid=Container_Data_Id, curname=eachDataId[0], newname=eachDataId[1] ) else: # if its not a tuple, then its cur_data_id result = DBUtil.InsertNewRecordInToTable(conn, "container_type_data", dataid=Container_Data_Id, curname=eachDataId ) if result == True: LogMessage(sModuleInfo, "Inserted Container data set for %s" % Data_Id_List, 4, result) if result != True: err_msg = LogMessage(sModuleInfo, "Failed to add container data set for %s:" % Data_Id_List, 4) return err_msg return Container_Data_Id
def deprecated(message, help=None, line_message="Deprecated", warning="Warning", trace=True, output_fn=_log): """This is a utility function used to warn of deprected calls.""" (frame, filename, line_number, function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[2] output = [] output.append(" ---- Deprecation {0}!".format(warning)) output.append("") output += [ " {0}".format(line.strip()) for line in iter(message.strip().splitlines()) ] output.append("") output.append(" -- File : {0}".format(filename)) output.append(" -- Line : {0}".format(line_number)) if function_name == "<module>": output.append(" -- Module : {0}".format(inspect.getmoduleinfo(filename))) else: output.append(" -- Function: {0}".format(function_name)) output.append("") for line in lines: output.append(" {0}".format(line.strip())) output.append(" {0}\__ {1}".format(" " * index, line_message)) if help: output.append("") output += [ " {0}".format(line.strip()) for line in iter(help.strip().splitlines()) ] if trace: output.append("") output.append(get_trace(skip=1)) output.append("") output_fn("\n".join(output))
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', help='Changes file in place', const=True, action='store_const') parser.add_argument('-p', help='Prints changes', const=True, action='store_const') parser.add_argument('files', nargs='*') args = parser.parse_args() files = [] for arg in args.files: for f in glob(arg): files.append(f) if not args.files: # Try to find files piped to us. files = [f for f in sys.stdin.readlines()] # Remove any non-Python files. py_files = [] for f in files: f = f.strip() mod = inspect.getmoduleinfo(f) if mod and mod[3] in (imp.PY_SOURCE,): py_files.append(f) for arg in py_files: parser = Parser(arg) if args.i: parser.inplace() elif args.p: parser.show() else: parser.check()
def search_for_an_item(dependency,step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name first_data_set=step_data[0] search_text=first_data_set[0][2] sTestStepReturnStatus = WebProgram.SearchItem(search_text) print sTestStepReturnStatus return sTestStepReturnStatus
def Restart(self): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: print "Restarting FW" return 'restart' except Exception, e: print "Exception %s" % e return False
def build_state_change_table(project_dir): retval = {} if os.path.isdir(project_dir): if os.path.isdir(os.path.join(project_dir, 'tests')): test_dir = os.path.join(project_dir, 'tests') test_list = os.listdir(test_dir) for test in test_list: print inspect.getmoduleinfo(os.path.join(test_dir, test)) else: msg = "'%s' is not a directory" logging.critical(msg) raise Exception(msg) else: msg = "'%s' is not a directory, let alone a project directory" logging.critical(msg) raise Exception(msg)
def go_to_webpage(dependency,step_data): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name #getting the first data set by this following lines first_data_set=step_data[0] web_link=first_data_set[0][2] sTestStepReturnStatus = WebProgram.OpenLink(web_link) print sTestStepReturnStatus return sTestStepReturnStatus
def get_caller_module(level=2): ''' return the name of the module that called the function that called this function, by default it assumes that the function that called this function was called from another module, to change this set level to the value of nested calls ''' return inspect.getmoduleinfo(inspect.stack()[level][1]).name
def getfilepathname_type(fpath): """Type for stored module as defined by *imp*.""" if not V3K: # for now the more frequent call if not os.path.exists(fpath): return ret = getmoduleinfo(fpath) if ret and ret[3] in (PY_SOURCE, PY_COMPILED, C_EXTENSION, PKG_DIRECTORY, C_BUILTIN, PY_FROZEN): return ret[3] else: if not os.path.exists(fpath): return # # the redundnacy of type-postfixes requires now prefix-analysis by '_scname' # # In [1]: from importlib.machinery import SOURCE_SUFFIXES, DEBUG_BYTECODE_SUFFIXES # ...: , OPTIMIZED_BYTECODE_SUFFIXES, BYTECODE_SUFFIXES, EXTENSION_SUFFIXES # # In [3]: SOURCE_SUFFIXES # Out[3]: ['.py'] # # In [4]: DEBUG_BYTECODE_SUFFIXES # Out[4]: ['.pyc'] # # In [5]: OPTIMIZED_BYTECODE_SUFFIXES # Out[5]: ['.pyc'] # # In [6]: BYTECODE_SUFFIXES # Out[6]: ['.pyc'] # # In [7]: EXTENSION_SUFFIXES # Out[7]: ['.cpython-36m-x86_64-linux-gnu.so', '.abi3.so', '.so'] x = _scname.findall(fpath) if x: x = x[0] # trust... else: x = os.path.splitext(fpath) if x[-1] in SOURCE_SUFFIXES: return __MT_SOURCE elif x[-1] in EXTENSION_SUFFIXES: return __MT_EXTENSION elif x[-1] in BYTECODE_SUFFIXES and not x[-2]: return __MT_COMPILED elif x[-1] in OPTIMIZED_BYTECODE_SUFFIXES and x[-2]: if x[-2] == 'opt-1': return __MT_COMPILED_OPT1 if x[-2] == 'opt-2': return __MT_COMPILED_OPT2 raise PySourceInfoError( "Unknown opt:" + str(x[-2]) + " " + str(fpath)) elif x[-1] in DEBUG_BYTECODE_SUFFIXES: return __MT_COMPILED_DEBUG return __MT_UNKNOWN
def which_scriptname_isit_whew_i_was_called_from(): import inspect # return inspect.stack() path = inspect.stack()[-1][1] # print "" # print "len:",len(path) # print "-->>>",path # print "" return inspect.getmoduleinfo(path).name
def get_title_of_element(id_path): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name title_of_ele = id_path.title.get() return True except Exception, e: print "%s > Exception Happened (%s)" % (sModuleInfo, e) CommonUtil.ExecLog(sModuleInfo, "Exception Happened (%s)" % e, 3) return False
def set_txt_value(id_path, txt): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name set_txt = id_path.value.set(txt) print "performed seting value to empty" return True except Exception, e: print "%s > Exception Happened (%s)" % (sModuleInfo, e) CommonUtil.ExecLog(sModuleInfo, "Exception Happened (%s)" % e, 3) return False
def close_app(dependency,step_data,temp_q): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: sTestStepReturnStatus = AndroidSupport.close() print sTestStepReturnStatus temp_q.put(sTestStepReturnStatus) return sTestStepReturnStatus except: temp_q.put("Failed") return "Failed"
def openActivity(package_name,activity_name): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: android_driver.start_activity(package_name,activity_name) return "passed" except Exception, e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Error_Detail = ((str(exc_type).replace("type ", "Error Type: ")) + ";" + "Error Message: " + str(exc_obj) +";" + "File Name: " + fname + ";" + "Line: "+ str(exc_tb.tb_lineno)) CommonUtil.ExecLog(sModuleInfo, "Unable to start WebDriver. %s"%Error_Detail, 3,local_run) return "failed"
def is_app_running(app_name): try: sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name process_list = app(u'System Events').processes.name.get() if app_name in process_list: return True else: return False except Exception, e: return CommonUtil.LogCriticalException(sModuleInfo, e)
def getXmlGuiClient(plugin=None, ef=1, use_inspect=False): '''Provide an access to an XML GUI client for a current plugin''' if plugin is None: if use_inspect: plugin = inspect.getmoduleinfo(inspect.stack()[ef + 1][1])[0] else: plugin = sys._getframe(1).f_globals['__name__'] kDebug('Getting XMLGUIClient for {}/{}/{}'.format(plugin, ef, use_inspect)) if plugin in _registered_xml_gui_clients: return _registered_xml_gui_clients[plugin]
def __init__(self, func, fallback=None, autojit_kw=None): self.func = func self.func_name = func.func_name module_name = inspect.getmoduleinfo(func.func_globals['__file__']).name module_name = '.'.join(['trackpy', module_name]) self.module_name = module_name self.autojit_kw = autojit_kw if fallback is not None: self.ordinary = fallback else: self.ordinary = func
def custom_import(name, *args, **kwargs): """Custom import hook to apply contracts to CeLMA modules""" new_import = name not in sys.modules mod = originalImport(name, *args, **kwargs) # pylint: disable-msg=W0142 if hasattr(mod, '__file__'): moduleInfo = getmoduleinfo(mod.__file__) if (new_import and name.startswith('%s.' % module_name) and moduleInfo is not None and moduleInfo[3] != C_EXTENSION): contract.checkmod(name) return mod
def sign_in(dependency,step_data,temp_q): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: username=step_data[0][0][1] password=step_data[0][1][1] sTestStepReturnStatus = AndroidSupport.login(username,password) print sTestStepReturnStatus temp_q.put(sTestStepReturnStatus) return sTestStepReturnStatus except: temp_q.put("Failed") return "Failed"
def open_activity(dependency,step_data,temp_q): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: activity_name=step_data[0][0][1] package_name=step_data[0][1][1] sTestStepReturnStatus = AndroidSupport.openActivity(package_name,activity_name) print sTestStepReturnStatus temp_q.put(sTestStepReturnStatus) return sTestStepReturnStatus except: temp_q.put("Failed") return "Failed"
def is_check_box_checked_unchecked(ElemId=None, ElemPath=None, ElemRole=None, ElemValue=None, ElemPosition=None): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: ElementName = [Key for Key, Value in Global.Ids.items() if Value == ElemId or Value == ElemPath] element = Find_Element(elem_id=ElemId, elem_path=ElemPath, elem_role=ElemRole, elem_value=ElemValue, elem_position=ElemPosition) if element != False and len(element) > 0: status = element[0].value.get() return status else: return "Critical" except Exception, e: return CommonUtil.LogCriticalException(sModuleInfo, e)
def name(self): """ Name of the module (not a qname). Use if this is a bit questinable as this is no way unique name for the module. By this name the module cannot be accessed again. + @str Simple name of the module. ? None = readonly = safe """ info = inspect.getmoduleinfo(self._module.__file__) assert (info) return info[0]
def name(self): """ Name of the module (not a qname). Use if this is a bit questinable as this is no way unique name for the module. By this name the module cannot be accessed again. + @str Simple name of the module. ? None = readonly = safe """ info = inspect.getmoduleinfo(self._module.__file__) assert(info) return info[0]
def close(): sModuleInfo = inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name try: CommonUtil.ExecLog(sModuleInfo,"Trying to close the app",1,local_run) android_driver.close_app() CommonUtil.ExecLog(sModuleInfo,"Closed app successfully",1,local_run) return "passed" except Exception, e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Error_Detail = ((str(exc_type).replace("type ", "Error Type: ")) + ";" + "Error Message: " + str(exc_obj) +";" + "File Name: " + fname + ";" + "Line: "+ str(exc_tb.tb_lineno)) CommonUtil.ExecLog(sModuleInfo, "Unable to start WebDriver. %s"%Error_Detail, 3,local_run) return "failed"
def _stack_walk_compact(): filename = None lineno = None current_frame = inspect.currentframe() # unwind until we hit a frame that's not from pymic's call stack while current_frame is not None: traceback = inspect.getframeinfo(current_frame) module = inspect.getmoduleinfo(traceback.filename) # TODO: is this test sufficient? if module.name not in _pymic_modules: filename = traceback.filename lineno = traceback.lineno break current_frame = current_frame.f_back return (filename, lineno)
def __init__(self, func, fallback=None, autojit_kw=None): self.func = func # This covers a Python 2/3 change not covered by six try: self.func_name = func.__name__ except AttributeError: self.func_name = func.func_name module_name = inspect.getmoduleinfo( six.get_function_globals(func)['__file__']).name module_name = '.'.join(['trackpy', module_name]) self.module_name = module_name self.autojit_kw = autojit_kw if fallback is not None: self.ordinary = fallback else: self.ordinary = func
def safeimport(path, forceload=0, cache={}): """Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a package path is specified, the module at the end of the path is returned, not the package at the beginning. If the optional 'forceload' argument is 1, we reload the module from disk (unless it's a dynamic extension).""" if forceload and path in sys.modules: # This is the only way to be sure. Checking the mtime of the file # isn't good enough (e.g. what if the module contains a class that # inherits from another module that has changed?). if path not in sys.builtin_module_names: # Python never loads a dynamic extension a second time from the # same path, even if the file is changed or missing. Deleting # the entry in sys.modules doesn't help for dynamic extensions, # so we're not even going to try to keep them up to date. info = inspect.getmoduleinfo(sys.modules[path].__file__) if info[3] != imp.C_EXTENSION: cache[path] = sys.modules[path] # prevent module from clearing del sys.modules[path] try: print "Trying to import module: %s" % path module = __import__(path) except: # Did the error occur before or after the module was found? (exc, value, tb) = info = sys.exc_info() if path in sys.modules: # An error occured while executing the imported module. raise ErrorDuringImport(sys.modules[path].__file__, info) elif exc is SyntaxError: # A SyntaxError occurred before we could execute the module. raise ErrorDuringImport(value.filename, info) elif exc is ImportError and \ split(lower(str(value)))[:2] == ['no', 'module']: # The module was not found. return None else: # Some other error occurred during the importing process. raise ErrorDuringImport(path, sys.exc_info()) for part in split(path, '.')[1:]: try: module = getattr(module, part) except AttributeError: return None return module
def __init__(self, plugin=None): self.instance = None if not plugin: # Guess module from caller frm = inspect.stack()[1] pluginmod = inspect.getmodule(frm[0]) (name, suffix, mode, module_type) = inspect.getmoduleinfo(pluginmod.__file__) # name = inspect.getmodulename(pluginmod) self.cls = getattr(pluginmod, name) elif isinstance(plugin, types.TypeType): # Got class - recommended usage self.cls = plugin elif isinstance(plugin, types.ModuleType): # Got Module (returned from import. Find class of same name # cache.load_module(module.__name__) # FIXME - iterate through all module attrs to find the class for name, obj in inspect.getmembers(plugin): if (hasattr(obj, "__bases__") and ion.plugin.base.IonPluginBase in obj.__bases__): self.cls = obj break else: LOG.error( "Unable to find class in module '%s' which implements IonPlugin", plugin.__name__, ) self.cls = plugin elif isinstance(plugin, ion.plugin.base.IonPluginBase): # Got plugin instance self.cls = plugin.__class__ self.instance = plugin elif isinstance(plugin, basestring): from ion.plugin.loader import cache self.cls = ion.plugin.loader.cache.load_module(plugin) else: LOG.fatal("Unable to recognize %s as plugin definition", plugin) raise ValueError( "PluginCLI must be called with a class instance or string class name" ) self.ret = None status = self.run() atexit.register(plugin_shutdown, self)
def _stack_walk_full(): stack = [] current_frame = inspect.currentframe() # unwind until we hit a frame that's not from pymic's call stack while current_frame is not None: traceback = inspect.getframeinfo(current_frame) module = inspect.getmoduleinfo(traceback.filename) # TODO: is this test sufficient? if module.name not in _pymic_modules: break current_frame = current_frame.f_back # continue to unwind, collection all stack frames seen while current_frame is not None: traceback = inspect.getframeinfo(current_frame) stack.append( (traceback.function, (traceback.filename, traceback.lineno))) current_frame = current_frame.f_back return stack
def _extract_from_toolkit(): """ Look at all the modules in opt/python/streams (opt/python/streams/*.py) and extract any spl decorated function as an operator. """ extractor = _Extractor() tk_dir = extractor._tk_dir tk_streams = os.path.join(tk_dir, 'opt', 'python', 'streams') print(tk_streams) if not os.path.isdir(tk_streams): # Nothing to do return sys.path.insert(1, tk_streams) tk_packages = os.path.join(tk_dir, 'opt', 'python', 'packages') if os.path.isdir(tk_packages): sys.path.insert(1, tk_packages) tk_modules = os.path.join(tk_dir, 'opt', 'python', 'modules') if os.path.isdir(tk_modules): sys.path.insert(1, tk_modules) for mf in glob.glob(os.path.join(tk_streams, '*.py')): print('Checking ', mf, 'for operators') (name, suffix, mode, mtype) = inspect.getmoduleinfo(mf) dynm = imp.load_source(name, mf) streams_python_file = inspect.getsourcefile(dynm) extractor._process_operators(dynm, name, streams_python_file, inspect.getmembers(dynm, inspect.isfunction)) extractor._process_operators(dynm, name, streams_python_file, inspect.getmembers(dynm, inspect.isclass)) langList = extractor._copy_globalization_resources() if extractor._cmd_args.verbose: print("Available languages for TopologySplpy resource:", langList) extractor._setup_info_xml(langList) # Now make the toolkit if required if extractor._cmd_args.make_toolkit: si = os.environ['STREAMS_INSTALL'] mktk = os.path.join(si, 'bin', 'spl-make-toolkit') mktk_args = [mktk, '--directory', extractor._cmd_args.directory, '--make-operator'] subprocess.check_call(mktk_args)
def __init__(self, source): if isinstance(source, basestring): self.path = source self.name = inspect.getmodulename(source) self.module = None self.load() elif (inspect.ismodule(source)): self.module = source self.name = source.__name__ path = source.__file__ info = inspect.getmoduleinfo(path) if info[1] == 'pyc': path = os.path.splitext(path)[0] + '.py' if os.path.isfile(path): self.path = path else: self.path = source.__file__ else: self.path = path
def getmoduleinfo(self): """Get information about modules. Return a tuple of values that describe how Python will interpret the file identified by path if it is a module, or None if it would not be identified as a module. The return tuple is (name, suffix, mode, mtype), where name is the name of the module without the name of any enclosing package, suffix is the trailing part of the file name (which may not be a dot-delimited extension), mode is the open() mode that would be used ('r' or 'rb'), and mtype is an integer giving the type of the module. mtype will have a value which can be compared to the constants defined in the imp module; see the documentation for that module for more information on module types. """ path = getattr(self.obj, '__file__', None) if path is None: return None return inspect.getmoduleinfo(path)
def get_clickable_location(id_path): sModuleInfo = ( inspect.stack()[0][3] + " : " + inspect.getmoduleinfo(__file__).name ) try: clickable_position = [] raw_position = id_path.position.get() raw_size = id_path.size.get() raw_position_x = int(raw_position[0]) raw_position_y = int(raw_position[1]) raw_size_x = int(raw_size[0]) raw_size_y = int(raw_size[1]) half_raw_size_x = raw_size_x / 2 half_raw_size_y = raw_size_y / 2 clickable_position_x = half_raw_size_x + raw_position_x clickable_position_y = half_raw_size_y + raw_position_y clickable_position = [clickable_position_x, clickable_position_y] return clickable_position except: print("Something went wrong ") return False
def DocDirectory(self, path): """ Return doc of all modules composing path directory by reading its __ini__.py """ ### init_file at first level ! init_file = os.path.join(path, '__init__.py') doc = "" ### if init_file exists in module if os.path.exists(init_file): ### get list of content filename lst = getFileListFromInit(init_file) if lst != []: # for each python filename, inspect its module info for fn in lst: fn_path = os.path.join(path, fn + '.py') t = inspect.getmoduleinfo(fn_path) if t is not None: name, suffix, mode, module_type = t doc += _("---------- %s module :\n")%fn+ \ _("\tname : %s\n")%name+ \ _("\tsuffix : %s\n")%suffix+ \ _("\tmode : %s\n")%mode+ \ _("\ttype of module : %s\n")%module_type+ \ _("\tpath : %s\n\n")%fn_path else: doc += _( "----------%s module not inspectable !\n") % fn #else: #pass #doc += _("%s is empty !\n")%init_file #else: #pass #doc += _("%s dont exist !\n")%init_file ### TODO take in charge also amd and cmd ! return doc
def debug(debugMessage, outStream=sys.stdout, newLine=True, lineNumber=None): import inspect if (DebugManager._verbose): newLineStr = newLine and '\n' \ or '' lineNumberStr = '' if lineNumber: lineNumberStr += '[Line ' + str(lineNumber) + ']: ' frame = inspect.currentframe().f_back func = frame.f_code prefix = "(" mi = inspect.getmoduleinfo(func.co_filename) if mi: prefix += mi.name + ":" prefix += func.co_name + ":" prefix += func.co_filename[func.co_filename. rfind('SourceProcessing') + len('SourceProcessing') + 1:] + ":" prefix += str(frame.f_lineno) + ")" outStream.write(prefix + lineNumberStr + debugMessage + newLineStr) outStream.flush()
def get_module(mod,path): print("Is Module ",inspect.ismodule(mod)) print("Memebers ",inspect.getmembers(mod)) #predicate is options print("Module Info ", inspect.getmoduleinfo(path)) print("Module Name ",inspect.getmodulename(path))
import platform import unittest import xml.etree.ElementTree class MyTest(unittest.TestCase): def test(self): self.assert_(True) # [deprecated-method] xml.etree.ElementTree.Element('tag').getchildren() # [deprecated-method] xml.etree.ElementTree.Element('tag').getiterator() # [deprecated-method] xml.etree.ElementTree.XMLParser('tag', None, None).doctype(None, None, None) # [deprecated-method] nntplib.NNTP(None).xpath(None) # [deprecated-method] inspect.getmoduleinfo(inspect) # [deprecated-method] inspect.getmodulename(inspect) # [deprecated-method] inspect.getargspec(None) # [deprecated-method] logging.warn("a") # [deprecated-method] platform.popen([]) # [deprecated-method] base64.encodestring("42") # [deprecated-method] base64.decodestring("42") # [deprecated-method] cgi.escape("a") # [deprecated-method] class SuperCrash(unittest.TestCase): def __init__(self): # should not crash. super(SuperCrash, self)()
def set_module_path(self, path): if path is not None and exists(path): self.name, suffix, mode, mtype = inspect.getmoduleinfo(path) sys.path.append(dirname(path)) self.m = __import__(self.name)
import inspect import sys import imp import os mainPath = os.environ['PYTHONPATH'] operation = sys.argv[1] if (operation == "MethodList"): classType = sys.argv[3] if (classType == "class"): filePath = sys.argv[2] name = inspect.getmoduleinfo(filePath).name loadedModule = imp.load_source(name, filePath) fullModulePath = os.path.dirname(loadedModule.__file__) fullModulePath = fullModulePath.replace(mainPath, "")[1:] fullModulePath = fullModulePath.replace("\\", ".") fullModulePath = fullModulePath.replace("/", ".") for className, data in inspect.getmembers(loadedModule, inspect.isclass): #if(className != "__init__" and hasattr(data, 'module')): if (className != "__init__"): if (fullModulePath != ""): print fullModulePath + "." + name + "." + className else: print name + "." + className else: filePath = sys.argv[2] className = sys.argv[3] name = inspect.getmoduleinfo(filePath).name loadedModule = imp.load_source(name, filePath) for name, data in inspect.getmembers(loadedModule, inspect.isclass): if (name == className.split(".")[-1]):
if 0: print inspect.getmembers(inspect)[0] # print inspect.getmembers(inspect) def isstr(obj): if isinstance(obj, str): return True return False if 0: print inspect.getmembers(inspect, isstr)[0] # #getmoduleinfo(path) if 0: m = inspect.getmoduleinfo('./test_inspect.py') print m print m.__class__ # #ismodule if 0: print 'inspect.ismodule(inspect) --> ',inspect.ismodule(inspect) # #isclass if 0: print 'inspect.isclass(inspect) --> ',inspect.isclass(inspect) print 'inspect.isclass(inspect.ModuleInfo) --> ',inspect.isclass(inspect.ModuleInfo) # #ismethod def func(): '''i am a function'''
def getcaller(): parent, pfile, pline, pfunction, lines, index = inspect.stack()[2] pmodule = inspect.getmoduleinfo(pfile)[0] pclass = getclass(parent) return (pmodule, pclass, pfunction, pfile, pline)
def __init__(self): super(BaseObject, self).__init__() self._file = inspect.getsourcefile(self.__class__) self._class_name = inspect.getmoduleinfo(self._file).name self._config = JSONConfig(class_name=self._class_name)
import os import sys # Check if file is provided and exists if len(sys.argv) >= 2: filename = sys.argv[1] else: filename = "test_example.py" if os.path.isfile(filename) is False: print "File %s does not exist" % filename sys.exit(0) # Check if file is source file and suffix is correct try: (name, suffix, mode, mtype) = inspect.getmoduleinfo(filename) except TypeError: print "Unable to determine module type %s" % filename else: mtype_name = { imp.PY_SOURCE: 'source', imp.PY_COMPILED: 'compiled', }.get(mtype, mtype) mode_description = { 'rb': '(read-binary)', 'U': '(Universal Newline)', }.get(mode, '') print "Name\t:%s" % name print "Suffix\t:%s" % suffix
def getcaller(): parent, pfile, pline, pfunction, lines, index = inspect.stack()[2] moduleinfo = inspect.getmoduleinfo(pfile) pmodule = moduleinfo[0] if moduleinfo else None pclass = getclass(parent) return (pmodule, pclass, pfunction, pfile, pline)
def find_plugins(path): '''Searches for module files that advertise themselves as pict plugins, in the directory tree rooted at path. ''' dw = os.walk(path) plugin_files = collections.OrderedDict() plugin_sources = collections.OrderedDict() forceRecompile = True # TODO make it a configuration variable for entry in dw: for fn in (os.path.join(entry[0], i) for i in entry[2]): if '.py' in fn and ('~' not in fn and 'bak' not in fn and 'old' not in fn and 'sav' not in fn and 'asv' not in fn): # skip backup files module_info = inspect.getmoduleinfo(fn) if module_info is not None: if module_info.name not in __avoid_modules__: # skip _THESE_ files module_file = open(fn, module_info.mode) try: for line in module_file: if '__pict_plugin__' in line: if module_info.module_type == imp.PY_COMPILED: plugin_files[module_info.name] = ( module_info, fn) elif module_info.module_type == imp.PY_SOURCE: plugin_sources[module_info.name] = ( module_info, fn) break except: module_file.close() finally: module_file.close() module_file.close() source_plugins = set(plugin_sources.keys()) compiled_plugins = set(plugin_files.keys()) source_and_compiled_plugins = source_plugins & compiled_plugins source_only_plugins = source_plugins - compiled_plugins compiled_only_plugins = compiled_plugins - source_plugins # (1) load compiled_only_plugins if len(compiled_only_plugins) > 0: for plugin in compiled_only_plugins: load_plugin(plugin_files[plugin]) # (2) load the rest of compiled_plugins (that also have source files), unless # forceRecompile is True, in which case load (and compile) _all_ source_plugins if len(source_and_compiled_plugins) > 0: for plugin in source_and_compiled_plugins: if forceRecompile: load_plugin(plugin_sources[plugin]) else: load_plugin(plugin_files[plugin]) # finally load source only plugins if len(source_only_plugins) > 0: for plugin in source_only_plugins: load_plugin(plugin_sources[plugin])