Example #1
0
def renameTextures(textures, input="zbrush", output="mari", prefix=None, preview=False):
    """
	Renames given textures.

	:param textures: Textures.
	:type textures: list
	:param input: Input format ( "mari", "mudbox", "zbrush" ).
	:type input: str
	:param output: Output format ( "mari", "mudbox", "zbrush" ).
	:type output: str
	:param prefix: Rename prefix.
	:type prefix: str
	:param preview: Only preview changes.
	:type preview: bool
	:return: Definition success.
	:rtype: bool
	"""

    for source, target in getTexturesNames(textures, input, output, prefix):
        if not os.path.exists(source):
            print("'{0}' | '{1}' file doesn't exists!".format(inspect.getmodulename(__file__), source))
            continue

        print(
            "'{0}' | {1} '{2}' texture to '{3}'.".format(
                inspect.getmodulename(__file__), "Rename ('Preview')" if preview else "Rename", source, target
            )
        )
        not preview and os.rename(source, target)

    return True
Example #2
0
    def iter_modules(self, prefix=''):
        if self.path is None or not os.path.isdir(self.path):
            return

        yielded = {}
        import inspect

        filenames = sorted(os.listdir(self.path))

        for fn in filenames:
            modname = inspect.getmodulename(fn)
            if modname=='__init__' or modname in yielded:
                continue

            path = os.path.join(self.path, fn)
            ispkg = False

            if not modname and os.path.isdir(path) and '.' not in fn:
                modname = fn
                try:
                    dircontents = os.listdir(path)
                except OSError:
                    # ignore unreadable directories like import does
                    dircontents = []
                for fn in dircontents:
                    subname = inspect.getmodulename(fn)
                    if subname=='__init__':
                        ispkg = True
                        break
                else:
                    continue    # not a package

            if modname and '.' not in modname:
                yielded[modname] = 1
                yield prefix + modname, ispkg
Example #3
0
    def iter_modules(self, prefix = ''):
        if self.path is None or not os.path.isdir(self.path):
            return
        yielded = {}
        import inspect
        try:
            filenames = os.listdir(self.path)
        except OSError:
            filenames = []

        filenames.sort()
        for fn in filenames:
            modname = inspect.getmodulename(fn)
            if modname == '__init__' or modname in yielded:
                continue
            path = os.path.join(self.path, fn)
            ispkg = False
            if not modname and os.path.isdir(path) and '.' not in fn:
                modname = fn
                try:
                    dircontents = os.listdir(path)
                except OSError:
                    dircontents = []

                for fn in dircontents:
                    subname = inspect.getmodulename(fn)
                    if subname == '__init__':
                        ispkg = True
                        break
                else:
                    continue

            if modname and '.' not in modname:
                yielded[modname] = 1
                yield (prefix + modname, ispkg)
Example #4
0
def _iter_file_finder_modules(importer, prefix=''):
    if importer.path is None or not os.path.isdir(importer.path):
        return
    yielded = {}
    import inspect
    try:
        filenames = os.listdir(importer.path)
    except OSError:
        filenames = []
    filenames.sort()
    for fn in filenames:
        modname = inspect.getmodulename(fn)
        while not modname == '__init__':
            if modname in yielded:
                pass
            path = os.path.join(importer.path, fn)
            ispkg = False
            if not modname and os.path.isdir(path) and '.' not in fn:
                modname = fn
                try:
                    dircontents = os.listdir(path)
                except OSError:
                    dircontents = []
                for fn in dircontents:
                    subname = inspect.getmodulename(fn)
                    while subname == '__init__':
                        ispkg = True
                        break
            while modname and '.' not in modname:
                yielded[modname] = 1
                yield (prefix + modname, ispkg)
Example #5
0
    def iter_modules(self, prefix=''):
        if self.path is None or not os.path.isdir(self.path):
            return

        yielded = {}
        import inspect

        filenames = os.listdir(self.path)
        filenames.sort()  # handle packages before same-named modules

        for fn in filenames:
            modname = inspect.getmodulename(fn)
            if modname=='__init__' or modname in yielded:
                continue

            path = os.path.join(self.path, fn)
            ispkg = False

            if not modname and os.path.isdir(path) and '.' not in fn:
                modname = fn
                for fn in os.listdir(path):
                    subname = inspect.getmodulename(fn)
                    if subname=='__init__':
                        ispkg = True
                        break
                else:
                    continue    # not a package

            if modname and '.' not in modname:
                yielded[modname] = 1
                yield prefix + modname, ispkg
Example #6
0
def displaySelectedPatches():
	"""
	This definition displays current selected patches.

	:return: Definition success. ( Boolean )
	"""
	
	patches = getSelectedPatches()
	print "%s | Current object: '%s'" % (inspect.getmodulename(__file__), mari.geo.current().name())
	print "%s | Selected patches: '%s'" % (inspect.getmodulename(__file__), patches)
	mari.utils.misc.message("Current object: '%s'\nSelected patches: '%s'" % (mari.geo.current().name(), ", ".join(patches)), title="Current Object Selected Patches")
	return True
Example #7
0
def toAlembic(parameters, arguments):
	"""
	Converts an Obj file to Alembic file.
	
	:param parameters: Command line parameters.
	:type parameters: object
	:param arguments: Command line arguments.
	:type arguments: object
	:return: Definition success.
	:rtype: bool
	"""

	inputFile = parameters.inputFile
	if inputFile is None:
		sys.stderr.write("!> {0} | No input file provided!\n".format(inspect.getmodulename(__file__)))
		return

	if not os.path.exists(inputFile):
		sys.stderr.write("!> {0} | '{1}' file doesn't exists'!\n".format(inspect.getmodulename(__file__), inputFile))
		return

	outputFile = os.path.abspath(parameters.outputFile if parameters.outputFile else re.sub(r"\.\w+$", ".abc", inputFile))

	exportAll = parameters.exportAll

	frameRange = parameters.frameRange
	try:
		frameIn, frameOut = frameRange.split("-")
	except ValueError:
		sys.stderr.write("!> {0} | The frame range format could not be determined!\n".format(inspect.getmodulename(__file__)))
		return
	
	not cmds.pluginInfo("AbcExport", q=True, loaded=True) and cmds.loadPlugin("AbcExport")	

	cmds.file(inputFile, o=True)

	# Processing ".obj" file normals.
	if re.search(r"\.obj$", inputFile, flags=re.IGNORECASE):
		for mesh in cmds.ls(type="mesh", long=True):
			cmds.polyNormalPerVertex(mesh, ufn=True)
			cmds.polySoftEdge(mesh, a=180, ch=False)

	if exportAll:
		jobCommand = "-frameRange {0} {1} -uvWrite -file {2}".format(frameIn, frameOut, outputFile)
	else:
		rootNodes = list(set([getRoot(mesh) for mesh in cmds.ls(type="mesh", long=True)]))
		rootFlags = " ".join(["-root {0}".format(rootNode) for rootNode in rootNodes])
		jobCommand = "-frameRange {0} {1} -uvWrite {2} -file {3}".format(frameIn, frameOut, rootFlags, outputFile)
	
	sys.stderr.write("{0} | Exporting to 'Alembic' with following job command: '{1}'\n".format(inspect.getmodulename(__file__), jobCommand))
	cmds.AbcExport(j=jobCommand)
	return True
Example #8
0
    def __init__(self, name=None, router=None,
                 error_handler=None):
        # Only set up a default log handler if the
        # end-user application didn't set anything up.
        if not logging.root.handlers and log.level == logging.NOTSET:
            formatter = logging.Formatter(
                "%(asctime)s: %(levelname)s: %(message)s")
            handler = logging.StreamHandler()
            handler.setFormatter(formatter)
            log.addHandler(handler)
            log.setLevel(logging.INFO)
        if name is None:
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])
        self.name = name
        self.router = router or Router()
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config()
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.debug = None
        self.sock = None
        self.processes = None

        # Register alternative method names
        self.go_fast = self.run
Example #9
0
    def __init__(self, name=None, router=None, error_handler=None,
                 load_env=True, request_class=None,
                 strict_slashes=False, log_config=None,
                 configure_logging=True):

        # Get name from previous stack frame
        if name is None:
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])

        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        self.name = name
        self.router = router or Router()
        self.request_class = request_class
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.configure_logging = configure_logging
        self.debug = None
        self.sock = None
        self.strict_slashes = strict_slashes
        self.listeners = defaultdict(list)
        self.is_running = False
        self.is_request_stream = False
        self.websocket_enabled = False
        self.websocket_tasks = set()

        # Register alternative method names
        self.go_fast = self.run
Example #10
0
def main(filename):
    """
    Uses inspect to return a list of function names and their description
    """
    classlist = {}
    methodlist = {}
    functionlist = {}
    print 'Filename:{0}'.format(filename)
    module = inspect.getmodulename(filename)
    print 'Module:{0}'.format(module)

    importedmodule = imp.load_source(module, filename)
    for name, data in inspect.getmembers(importedmodule):
        if inspect.isclass(data):
            classlist[name] = data.__doc__
        elif inspect.ismethod(data):
            methodlist[name] = data.__doc__
        elif inspect.isfunction(data):
            functionlist[name] = data.__doc__

    print "Functions: "
    for key in functionlist.keys():
        print '{0}'.format(key)

    print "Function / document"
    for key, value in functionlist.items():
        print '{0} {1}'.format(key, value)
Example #11
0
def _getModuleCallerInfo():
    # This works with CPython (Maya); I don't give a f**k if it doesn't
    # work with other Python implementations! Seriously... 'Portable' my ass!

    # Frame object example (tuple)
    # ------------------------------------------------------------------
    # (<frame object at 0x000000012D1DEB88>, 
    #  'C:\\Users\\guido.pollini\\Desktop\\MuTools\\MuTools\\MuCore.py', 
    #  223, 
    #  '<module>', 
    #  ['reload(MuTools.MuUtils)\n'], 
    #  0
    # )
    #
    # Note that item [1] is the module path! 

    outerFrames = inspect.getouterframes(inspect.currentframe())

    # Actual stack (in this special case, we need item [2])
    # ---------------------------------------------------------------------
    #     (0) _getModuleCallerInfo                      (Here)
    #     (1) moduleLoadingMessage/moduleLoadedMessage  (Here)
    # ==> (2) the caller module                         (The caller module)
    #     (3) ...                                       (Irrelevant)
    #     (4) ...                                       ...
    #     ...

    callerStackIndex = 2 
    moduleName = inspect.getmodulename(outerFrames[callerStackIndex][1])
    moduleFile = outerFrames[callerStackIndex][1]
    del outerFrames

    return (moduleName, moduleFile)
Example #12
0
def debug(text): #pylint: disable=unused-variable
  import inspect, os, sys
  global colourClear, colourDebug
  global verbosity
  if verbosity <= 2:
    return
  outer_frames = inspect.getouterframes(inspect.currentframe())
  nearest = outer_frames[1]
  try:
    if len(outer_frames) == 2: # debug() called directly from script being executed
      try:
        origin = '(' + os.path.basename(nearest.filename) + ':' + str(nearest.lineno) + ')'
      except AttributeError: # Prior to Python 3.5
        origin = '(' + os.path.basename(nearest[1]) + ':' + str(nearest[2]) + ')'
    else: # Some function has called debug(): Get location of both that function, and where that function was invoked
      try:
        filename = nearest.filename
        funcname = nearest.function + '()'
      except: # Prior to Python 3.5
        filename = nearest[1]
        funcname = nearest[3] + '()'
      modulename = inspect.getmodulename(filename)
      if modulename:
        funcname = modulename + '.' + funcname
      origin = funcname
      caller = outer_frames[2]
      try:
        origin += ' (from ' + os.path.basename(caller.filename) + ':' + str(caller.lineno) + ')'
      except AttributeError:
        origin += ' (from ' + os.path.basename(caller[1]) + ':' + str(caller[2]) + ')'
      finally:
        del caller
    sys.stderr.write(os.path.basename(sys.argv[0]) + ': ' + colourDebug + '[DEBUG] ' + origin + ': ' + text + colourClear + '\n')
  finally:
    del nearest
Example #13
0
 def globaltrace_lt(self, frame, why, arg):
     """
     Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'.
     """
     if os.getpid() != self.pid:
         return
     if why == "call":
         (filename, lineno, funcname, context, lineindex) = inspect.getframeinfo(frame, 0)
         # if DEBUG_MODE and not filename:
         #     print "%s.globaltrace(frame: %s, why: %s, arg: %s): filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,)
         if filename:
             modulename = inspect.getmodulename(filename)
             if modulename is not None:
                 ignore_it = self.ignore.names(filename, modulename)
                 # if DEBUG_MODE and not self.blabbed.has_key((filename, modulename,)):
                 #     self.blabbed[(filename, modulename,)] = None
                 #     print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s\n" % (self, frame, why, arg, filename, modulename, ignore_it,)
                 if not ignore_it:
                     if self.trace:
                         print " --- modulename: %s, funcname: %s" % (modulename, funcname)
                     # if DEBUG_MODE:
                     #     print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s -- about to localtrace\n" % (self, frame, why, arg, filename, modulename, ignore_it,)
                     return self.localtrace
         else:
             # XXX why no filename?
             return None
Example #14
0
    def __init__(self, queue, fn, routes=None):
        routes = routes or []

        self.routes = routes
        self.fn = fn
        # we need either a reference to the containing module
        # or to the containing object (instance or class)
        self.parent = None
        self.fn_type = None
        if inspect.ismethod(fn):
            self.fn_type = 'method'
            try:
                self.parent = dill.dumps(fn.__self__)
            except: # TODO what kind of exception is it
                raise ValueError("Instance containing method couldn't be marshalled")
        elif inspect.isfunction(fn):
            self.fn_type = 'function'
        else:
            raise TypeError("Job must be constructed with a function or method")
        self.mod = inspect.getmodulename(
                inspect.getmodule(fn).__file__)
        self.directory = os.getcwd()
        self.created = time.time()
        self.queue = queue
        self.args = None
        self.varargs = None
        self.kwargs = None

        self.persister = get_backend(queue.backend)(
                conn_url=queue.conn_url,
                dbname=queue.dbname)
Example #15
0
def run():
    call = request.json

    function_name = call["function_name"]
    function_args = call["args"]
    function_path = call["function_file"]
    function_kwargs = call["kwargs"]
    # logger.warning("file:%s"%(function_path))
    # logger.warning("file path:%s"% (os.getcwd()))
    module_name = inspect.getmodulename(function_path)
    # logger.warning(module_name)
    s_file = open(function_path, 'U')
    s_description = ('.py', 'U', 1)

    # Import the module or fetch it if already imported.
    with imported_modules_lock:
        if imported_modules.get(module_name):
            module = imported_modules[module_name]
        else:
            module = imp.load_module(module_name, s_file, function_path, s_description)
            imported_modules[module_name] = module

    function = getattr(module, function_name)
    logger.info("server starting: %s %s %s", function.__name__, function_args, function_kwargs)
    _run_in_thread(function, *function_args, **function_kwargs)
    return jsonify({"ok": "ok"})
Example #16
0
    def get_reference(self, reference):
        from .document import Document

        if reference is None:
            return reference

        result = None
        if isinstance(reference, string_types):
            stack = inspect.stack()
            for _ in stack:
                if _[1] is not None:
                    name = inspect.getmodulename(_[1])
                    _ = imp.find_module(name, [os.path.dirname(_[1])])
                    fp, _ = _[0], _[1:] 
                    try:
                        module = imp.load_module(name, fp, *_)
                        result = getattr(module, reference)
                        break
                    except:
                        pass
                    finally:
                        if fp:
                            fp.close()
                    
        elif issubclass(reference, Document):
            result = reference

        if result is None:
            raise Exception("Couldn't find %s" % reference)

        return result
Example #17
0
def _IterModules(file_list, prefix=None):
  """Yields module names from given list of file paths with given prefix."""
  yielded = set()
  if prefix is None:
    prefix = ''
  for file_path in file_list:
    if not file_path.startswith(prefix):
      continue

    file_path_parts = file_path[len(prefix):].split(os.sep)

    if (len(file_path_parts) == 2
        and file_path_parts[1].startswith('__init__.py')):
      if file_path_parts[0] not in yielded:
        yielded.add(file_path_parts[0])
        yield file_path_parts[0], True

    if len(file_path_parts) != 1:
      continue

    modname = inspect.getmodulename(file_path_parts[0])
    if modname == '__init__':
      continue

    if modname and '.' not in modname and modname not in yielded:
      yielded.add(modname)
      yield modname, False
def renameUdimToMariNames(parameters, arguments):
	"""
	This definition renames Udim matched files to Mari patch number files.

	:param udim: Udim to convert. ( String )
	:param parameters: Command line parameters. ( Object )
	:param arguments: Command line arguments. ( Object )
	:return: Definition success. ( Boolean )
	"""

	if os.path.exists(parameters.sourceDirectory):
		files = glob.glob("{0}/*{1}".format(parameters.sourceDirectory, parameters.filesExtensions))
		for file in files:
			search = re.search(r"({0})".format(UDIM_FILTER), file)
			if not search:
				continue
			patchNumber = getMariPatchNumberFromUdim(search.group(0))
			if parameters.renamePrefix:
				name = "{0}{1}.{2}".format(parameters.renamePrefix, str(patchNumber), parameters.filesExtensions)
			else:
				name = re.sub(r"({0})".format(UDIM_FILTER), str(patchNumber), file)
			
			print("'{0}' | Rename '{1}' file to '{2}'.".format(inspect.getmodulename(__file__),file, name))
			os.rename(file, name)
		return True
Example #19
0
def list_modules(dirname):
    modules = []
    for path in glob(os.path.join(dirname, '*.py')):
        module = inspect.getmodulename(path)
        if module not in ('__init__', 'base'):
            modules.append(module)
    return modules
    def iter_zipimport_modules(importer, prefix=''):
        dirlist = zipimport._zip_directory_cache[importer.archive].keys()
        dirlist.sort()
        _prefix = importer.prefix
        plen = len(_prefix)
        yielded = {}
        import inspect
        for fn in dirlist:
            if not fn.startswith(_prefix):
                continue

            fn = fn[plen:].split(os.sep)

            if len(fn)==2 and fn[1].startswith('__init__.py'):
                if fn[0] not in yielded:
                    yielded[fn[0]] = 1
                    yield fn[0], True

            if len(fn)!=1:
                continue

            modname = inspect.getmodulename(fn[0])
            if modname=='__init__':
                continue

            if modname and '.' not in modname and modname not in yielded:
                yielded[modname] = 1
                yield prefix + modname, False
Example #21
0
def logModuleCaller():
    # This works with CPython (Maya) and you can't use the generic 'getCaller'
    # because in this case, OR YOU CAN??? CHECK IT BETTER


    # Get the list of outer frames <6-uples>
    outerFrames = inspect.getouterframes(inspect.currentframe())
    # Frame 6-uple:
    # 0 --> <frame object at 0x000000012D1DEB88>
    # 1 --> <str> module caller path 
    # 2 --> <int>
    # 3 --> <module> module caller obj
    # 4 --> <list> caller Name, 
    # 5 --> <int>

    # Actual outer frames in the stack (in this special case, we need item 2)
    #     (0) logModuleCaller   (Here)
    #     (1) Log.__init__      (Here)
    # ==> (2) the caller module (The caller module, where Log(...) was called)
    #     (3) ...                                       ...
    #     ...
    callerStackIndex = 2 
    moduleName = inspect.getmodulename(outerFrames[callerStackIndex][1])
    del outerFrames

    return moduleName
Example #22
0
 def _get_module_name(self):
     """Get the name of the module containing the class inheriting from this
     class, i.e., the name of the plugin.
     """
     current_class = inspect.getfile(self.__class__)
     current_module = inspect.getmodulename(current_class)
     return current_module
Example #23
0
    def index(self, path):
        """
        Index all *Recipes* in the path.

        For each file, the Recipe subclass should be named after the file.
        So for path/ag.py should have a class called Ag.

        Args:
            path: The folder containing recipes to index.
        """
        try:
            check_package(path)
            sys.path.insert(0, os.path.dirname(path))

            new_recs = [inspect.getmodulename(fname) for fname
                        in glob.glob(os.path.join(path, '*.py'))]
            if '__init__' in new_recs:
                new_recs.remove('__init__')
            if 'setup' in new_recs:
                new_recs.remove('setup')

            mod = os.path.basename(path)
            for cls in new_recs:
                obj = self.recipe_obj(mod, cls)
                self.rdb.update({cls: obj})
        finally:
            if os.path.dirname(path) in sys.path:
                sys.path.remove(os.path.dirname(path))
Example #24
0
 def __init__(self, configurationsDictionary = {}, loggingFileName = "", defaultLoggingLevel = "INFO"):
     """Constructor.
     
     Root logger configuration is done here using :func:`logging.basicConfig`. This means that *loggingFileName* and  *defaultLoggingLevel* parameters are defined by the first module in an import hierarchy that instantiate an :class:`EchoHandler` object, as subsequent calls to :func:`logging.basicConfig` have no effect. So, for example, when running the :doc:`client<client>`, it is the first module to instantiate an :class:`EchoHandler` object. The :doc:`client<client>` module imports the :mod:`crawler` module, but as :mod:`crawler` is the second module in the hierarchy, it will use the root logger configuration defined in :doc:`client<client>`, despite any local settings of *loggingFileName* and *defaultLoggingLevel*.
     
     Args:
         * *configurationsDictionary* (dict): Holds values for the three configuration options supported: verbose (bool), logging (bool) and loggingpath (str).
         * *loggingFileName* (str): Name of the file used to save logging messages.
         * *defaultLoggingLevel* (str): Level at which the root logger must be set. Supports any of the :ref:`level names <python:levels>` defined in Python's built-in logging module.
         
     .. seealso::
     
         Python's built-in :mod:`logging <python:logging>` module documentation.
     
     """
     self._extractConfig(configurationsDictionary)
     
     # Identify calling module
     frameRecords = inspect.stack()[1]
     self.callingModuleName = inspect.getmodulename(frameRecords[1])
     
     # Set up logging
     if not os.path.exists(self.loggingPath): os.makedirs(self.loggingPath)
     if (not loggingFileName): loggingFileName = self.callingModuleName + ".log"
     logging.basicConfig(format=u"%(asctime)s %(name)s %(levelname)s: %(message)s", datefmt="%d/%m/%Y %H:%M:%S", 
                         filename=os.path.join(self.loggingPath, loggingFileName), filemode=self.loggingFileMode, level=getattr(logging, defaultLoggingLevel))
     self.logger = logging.getLogger(self.callingModuleName)
Example #25
0
    def _name_for_module(self, module_globals, filename):
        """Get the name of the module for a set of globals and file name.

        For configurability's sake, we allow __main__ modules to be matched by
        their importable name.

        If loaded via runpy (aka -m), we can usually recover the "original"
        full dotted module name, otherwise, we resort to interpreting the
        file name to get the module's name.  In the case that the module name
        can't be determined, None is returned.

        """
        dunder_name = module_globals.get('__name__', None)

        if isinstance(dunder_name, str) and dunder_name != '__main__':
            # This is the usual case: an imported module.
            return dunder_name

        loader = module_globals.get('__loader__', None)
        for attrname in ('fullname', 'name'):   # attribute renamed in py3.2
            if hasattr(loader, attrname):
                fullname = getattr(loader, attrname)
            else:
                continue

            if isinstance(fullname, str) and fullname != '__main__':
                # Module loaded via: runpy -m
                return fullname

        # Script as first argument to Python command line.
        inspectedname = inspect.getmodulename(filename)
        if inspectedname is not None:
            return inspectedname
        else:
            return dunder_name
Example #26
0
    def load(path):
        """
        Load a script by using a path.
        :returns: Loaded script module-
        :raise: ImportError, when script module cannot be loaded.
        """
        module_name    = inspect.getmodulename(path).replace("-", "_")
        module_dirname = os.path.dirname(path)
        if not module_dirname:
            module_dirname = os.curdir
        if not os.path.exists(path):
            raise ImportError("File not found: %s" % path)
        module_dirnamea = os.path.abspath(module_dirname)
        if not sys.path or module_dirnamea != sys.path[0]:
            sys.path.insert(0, module_dirnamea)

        module = None
        try:
            module = __import__(module_name)
            # module.__name__ = module_name
            # module.__file__ = path
        except ImportError, e:
            print "IMPORT-ERROR: %s (file=%s, curdir=%s)" % \
                  (module_name, path, os.getcwd())
            sys.stderr.write("Cannot import: %s\n" % e)
            for index, searchpath in enumerate(sys.path):
                print "  %2s.  %s" % (index, searchpath)
            raise
Example #27
0
def getmodule(pos=2):
    # stack returns a list of tuples containg frame information
    # First element of the list the is current frame, caller is 1
    frameinfo = inspect.stack()[pos]
    modname = inspect.getmodulename(frameinfo[1])
    #modname = inspect.getmodule(frameinfo[0]).__name__
    return modname
Example #28
0
 def _getName(self):
     retmod = "Module"
     frame, module, line, function, context, index = inspect.stack()[2]
     try:
         retmod = inspect.getmodulename(module)
     except:
         pass
     return retmod
Example #29
0
 def __init__(self,mapred):
     self._mapred = mapred
     self._source_file = inspect.getfile(self._mapred.__class__)
     self._module_name = self._mapred.__class__.__module__
     if self._module_name == '__main__':
         self._module_name = inspect.getmodulename(self._source_file)
    
     self._class_name = self._mapred.__class__.__name__
def runtests():
    import inspect
    thismodule = __import__(inspect.getmodulename(__file__))
    for name in dir(thismodule):
        obj = getattr(thismodule, name)
        if inspect.isfunction(obj) and name.startswith('test_'):
            obj()
            print name, "tests passed!"
Example #31
0
File: app.py Project: qwIvan/sanic
    def __init__(self,
                 name=None,
                 router=None,
                 error_handler=None,
                 load_env=True):
        # Only set up a default log handler if the
        # end-user application didn't set anything up.
        if not logging.root.handlers and log.level == logging.NOTSET:
            formatter = logging.Formatter(
                "%(asctime)s: %(levelname)s: %(message)s")
            handler = logging.StreamHandler()
            handler.setFormatter(formatter)
            log.addHandler(handler)
            log.setLevel(logging.INFO)

        # Get name from previous stack frame
        if name is None:
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])

        self.name = name
        self.router = router or Router()
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.debug = None
        self.sock = None
        self.listeners = defaultdict(list)
        self.is_running = False
        self.websocket_enabled = False
        self.websocket_tasks = []

        # Register alternative method names
        self.go_fast = self.run
Example #32
0
    def download(self, dload_url, torrent_name, load):
        """
        Torrent download method.

        Used to download .torrent file.
        Torrent is downloaded in ~/Downloads/torrench/
        """
        try:
            mod = inspect.getmodulename(inspect.stack()[1][1])
            modules_to_exclude = ['linuxtracker', 'distrowatch']
            self.logger.debug("Download begins...")
            home = os.path.expanduser(os.path.join('~', 'Downloads'))
            downloads_dir = os.path.join(home, 'torrench')
            self.logger.debug("Default download directory: %s",
                              (downloads_dir))
            if mod not in modules_to_exclude:
                downloads_dir = os.path.join(downloads_dir, mod)
            if not os.path.exists(downloads_dir):
                self.logger.debug("download directory does not exist.")
                os.makedirs(downloads_dir)
                self.logger.debug("created directory: %s", (downloads_dir))

            torrent_file = os.path.join(downloads_dir, torrent_name)
            with open(torrent_file, "wb") as file:
                print("Downloading torrent...")
                response = requests.get(dload_url)
                file.write(response.content)
                self.logger.debug("Download complete!")
                print("Download complete!")
                print("\nSaved in %s\n" % (downloads_dir))
                self.logger.debug("Saved in %s", (downloads_dir))
            # Load torrent to client
            if load == 1:
                self.load_torrent(torrent_file)
        except KeyboardInterrupt as e:
            self.logger.exception(e)
            print("\nAborted!\n")
Example #33
0
def show(app=None, **config):

    frame_records = inspect.stack()[1]
    calling_module = inspect.getmodulename(frame_records[1])
    python_file = os.path.basename(sys.argv[0])[:-3]

    if app is None:
        fitting_models = _find_subclasses_in_module(App, calling_module, [])
        assert len(fitting_models) == 1, 'show() called without model but detected %d possible classes: %s' % (len(fitting_models), fitting_models)
        app = fitting_models[0]

    if inspect.isclass(app) and issubclass(app, App):
        app = app()

    called_from_main = inspect.getmodule(app.__class__).__name__ == '__main__' or calling_module == python_file

    app.prepare()

    display = None
    if DEFAULT_DISPLAY_CLASS is not None:
        display = DEFAULT_DISPLAY_CLASS(app)
        display.configure(config)
        display.setup()
    # --- Autorun ---
    if AUTORUN:
        if display is None:
            app.info('Starting execution because autorun is enabled.')
            app.play()  # asynchronous call
        else:
            display.play()
    # --- Show ---
    if display is None:
        warnings.warn('show() has no effect because no display is available. To use the web interface, run $ pip install phiflow[gui]')
        return app
    else:
        return display.show(called_from_main)  # blocking call
Example #34
0
def load_suite_from_module(mod):
    # TODO: find a better way to workaround circular import
    from lemoncheesecake.suite.definition import get_metadata_next_rank

    suite_info = getattr(mod, "SUITE")
    suite_condition = suite_info.get("conditional")
    if suite_condition is not None and not suite_condition(mod):
        raise VisibilityConditionNotMet()

    suite_name = inspect.getmodulename(inspect.getfile(mod))

    try:
        suite_description = suite_info["description"]
    except KeyError:
        raise InvalidMetadataError("Missing description in '%s' suite information" % mod.__file__)

    suite = Suite(mod, suite_name, suite_description)
    suite.tags.extend(suite_info.get("tags", []))
    suite.properties.update(suite_info.get("properties", []))
    suite.links.extend(suite_info.get("links", []))
    suite.rank = suite_info.get("rank", get_metadata_next_rank())

    for hook_name in SUITE_HOOKS:
        if hasattr(mod, hook_name):
            suite.add_hook(hook_name, getattr(mod, hook_name))

    for test in load_tests_from_functions(get_test_functions_from_module(mod)):
        suite.add_test(test)

    for test in get_generated_tests(mod):
        suite.add_test(test)

    for sub_suite in load_suites_from_classes(get_suite_classes_from_module(mod)):
        suite.add_suite(sub_suite)

    return suite
Example #35
0
    def _extract_api_module(self):
        self.module_infos = []
        for f in os.listdir(self.target_dir):
            if not f.endswith(".py"):
                continue
            f_rel_path = os.path.relpath(
                os.path.join(self.target_dir, f),
                self.fe_dir,
            )
            f_module_path = f_rel_path.replace(sep, ".")
            f_module = pydoc.safeimport(inspect.getmodulename(f_module_path))

            for name, api_module in inspect.getmembers(f_module):
                if inspect.getmodule(api_module) != f_module:
                    continue
                if name.startswith('_'):
                    continue

                # load -> cifar10.load
                substitue_name = f"{f.split('.')[-2]}.{name}"

                self.module_infos.append(
                    [name, api_module, substitue_name, f_rel_path]
                )
Example #36
0
def download_to_file(url, file):
    frame_records = stack()[1]
    caller = getmodulename(frame_records[1]).upper()

    user_agent = {
        "User-agent":
        "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0"
    }
    try:
        logging.info(f'download_to_file - fetching url: {url}')
        r = requests.head(url, headers=user_agent)
        url_datetime = parsedate(r.headers['Last-Modified']).astimezone()
        file_datetime = datetime.datetime.fromtimestamp(
            path.getmtime(get_abspath_source_file(file))).astimezone()

        if (url_datetime > file_datetime):
            logging.info(
                '{} File on server is newer, so downloading update to {}'.
                format(caller, get_abspath_source_file(file)))
            actual_download_to_file(url, file, user_agent)
        else:
            logging.info(
                '{} File on server is older, nothing to do'.format(caller))
    except KeyError as exc:
        logging.warning(
            '{} KeyError in the headers. the {} header was not sent by server {}. Downloading file'
            .format(caller, str(exc), url))
        actual_download_to_file(url, file, user_agent)
    except FileNotFoundError as exc:
        logging.info("{} File didn't exist, so downloading {} from {}".format(
            caller, file, url))
        actual_download_to_file(url, file, user_agent)
    except Exception as exc:
        logging.warning('{} General exception occured: {}.'.format(
            caller, str(exc)))
        actual_download_to_file(url, file, user_agent)
Example #37
0
 def wrapper(*args, **kwargs):
     for fr in inspect.stack():
         if inspect.getmodulename(fr[1]) == 'loaddata':
             return
     signal_handler(*args, **kwargs)
Example #38
0
def module_name():
    from inspect import getmodulename, getfile
    return getmodulename(getfile(lambda x: None))
Example #39
0
def tqdm_proxy(iterable=None, *, logger=None, level=logging.INFO, **kwargs):
    """
    Useful as an (almost) drop-in replacement for ``tqdm`` which can be used
    in EITHER an interactive console OR a script that logs to file.
    
    Automatically detects whether or not sys.stdout is a file or a console,
    and configures tqdm accordingly.
    
    - If your code is running from an interactive console, this acts like plain ``tqdm``.
    - If your code is running from an ipython notebook, this acts like ``tqdm_notebook``.
    - If your code is running from a batch script (i.e. printing to a log file, not the console),
      this code uses the supplied logger periodically output a textual progress bar.
      If no logger is supplied, a logger is automatically created using the name of
      the calling module. 
    
    Example:

        for i in tqdm_proxy(range(1000)):
            # do some stuff

    Note for JupyterLab users:
    
        If you get errors in this function, you need to run the following commands:
        
            conda install -c conda-forge ipywidgets
            jupyter nbextension enable --py widgetsnbextension
            jupyter labextension install @jupyter-widgets/jupyterlab-manager
        
        ...and then reload your jupyterlab session, and restart your kernel.
    """
    assert 'file' not in kwargs, \
        "There's no reason to use this function if you are providing your own output stream"

    # Special case for tqdm_proxy(range(...))
    if iterable is not None and isinstance(iterable,
                                           range) and 'total' not in kwargs:
        kwargs['total'] = (iterable.stop - iterable.start) // iterable.step

    try:
        import ipykernel.iostream
        from tqdm import tqdm_notebook
        if isinstance(sys.stdout, ipykernel.iostream.OutStream):
            return tqdm_notebook(iterable, **kwargs)
    except ImportError:
        pass

    _tqdm = tqdm
    _file = None
    disable_monitor = False

    if not _file and os.isatty(sys.stdout.fileno()):
        _file = sys.stdout
    else:
        if logger is None:
            frame = inspect.stack()[1]
            modname = inspect.getmodulename(frame[1])
            if modname:
                logger = logging.getLogger(modname)
            else:
                logger = logging.getLogger("unknown")

        _file = TqdmToLogger(logger, level)

        # The tqdm monitor thread messes up our 'miniters' setting, so disable it.
        disable_monitor = True

        if 'ncols' not in kwargs:
            kwargs['ncols'] = 100

        if 'miniters' not in kwargs:
            # Aim for 5% updates
            if 'total' in kwargs:
                kwargs['miniters'] = kwargs['total'] // 20
            elif hasattr(iterable, '__len__'):
                kwargs['miniters'] = len(iterable) // 20

    kwargs['file'] = _file
    bar = _tqdm(iterable, **kwargs)
    if disable_monitor:
        bar.monitor_interval = 0
    return bar
Example #40
0
def getTexturesNames(textures, input="zbrush", output="mari", prefix=None):
    """Renames given textures.

    :param textures: Textures.
    :type textures: list
    :param input: Input format ( "mari", "mudbox", "zbrush" ).
    :type input: str
    :param output: Output format ( "mari", "mudbox", "zbrush" ).
    :type output: str
    :param prefix: Rename prefix.
    :type prefix: str
    :return: Converted textures names.
    :rtype: list

    .. code-block:: python

        getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"])
        #[(u'Diffuse_u0_v0.exr', u'Diffuse_1001.exr'), (u'Diffuse_u9_v0.exr', u'Diffuse_1010.exr')]
        getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"], "zbrush", "mudbox")
        #[(u'Diffuse_u9_v0.exr', u'Diffuse_u10_v1.exr'), (u'Diffuse_u0_v0.exr', u'Diffuse_u1_v1.exr')]
        getTexturesNames(["Diffuse_1001.exr", "Diffuse_1010.exr"], "mari", "zbrush")
        #[(u'Diffuse_1001.exr', u'Diffuse_u0_v0.exr'), (u'Diffuse_1010.exr', u'Diffuse_u9_v0.exr')]
        getTexturesNames(["Diffuse_1001.exr", "Diffuse_1010.exr"], "mari", "mudbox")
        #[(u'Diffuse_1001.exr', u'Diffuse_u1_v1.exr'), (u'Diffuse_1010.exr', u'Diffuse_u10_v1.exr')]
        getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"], prefix="")
        #[(u'Diffuse_u0_v0.exr', u'1001.exr'), (u'Diffuse_u9_v0.exr', u'1010.exr')]
        getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"], prefix="Color_")
        #[(u'Diffuse_u0_v0.exr', u'Color_1001.exr'), (u'Diffuse_u9_v0.exr', u'Color_1010.exr')]

    """

    inputMethod = "udim" if input in ("mudbox", "zbrush") else "patch"
    outputMethod = "udim" if output in ("mudbox", "zbrush") else "patch"
    pattern = UDIM_PATTERN if inputMethod == "udim" else PATCH_PATTERN

    offsetUdim = lambda x, y: (x[0] + y, x[1] + y)

    if input == "zbrush" and output == "mudbox":
        textures = reversed(textures)

    texturesMapping = []
    for texture in textures:
        basename = os.path.basename(texture)
        search = re.search(r"({0})".format(pattern), basename)
        if not search:
            print("'{0}' | '{1}' file doesn't match '{2}' pattern!".format(
                inspect.getmodulename(__file__), texture, inputMethod.title()))
            continue

        if inputMethod == "udim":
            udim = [int(value[1:]) for value in search.group(0).split("_")]
        elif inputMethod == "patch":
            udim = udimFromPatch(int(search.group(0)))

        udim = offsetUdim(udim, -1) if input == "mudbox" else udim
        udim = offsetUdim(udim, 1) if output == "mudbox" else udim

        if outputMethod == "udim":
            outputAffix = "u{0}_v{1}".format(*udim)
        elif outputMethod == "patch":
            outputAffix = patchFromUdim(udim)

        if prefix is not None:
            path = os.path.join(
                os.path.dirname(texture),
                "{0}{1}{2}".format(prefix, outputAffix,
                                   os.path.splitext(texture)[-1]))
        else:
            path = os.path.join(
                os.path.dirname(texture),
                re.sub(r"({0})".format(pattern), str(outputAffix), basename))

        texturesMapping.append((texture, path))

    return texturesMapping
Example #41
0
import inspect, pyclbr


def RunUnit(obj, clsName):
    print "Unittests for: %s..." % clsName,
    cnt = 0
    try:
        while True:
            s = obj.getValue()
            obj.next()
            cnt += 1

    except GeneratorCompleted:
        print "%d tests found." % cnt


if __name__ == "__main__":
    print "\n -- Running A Quick Unittest for %s --\n" % __file__
    mod = inspect.getmodulename(__file__)
    for clsName in pyclbr.readmodule(mod):
        cls = globals()[clsName]
        if str(cls).find('__main__') > -1 and hasattr(cls, 'next') and hasattr(
                cls, 'getValue'):
            try:
                RunUnit(cls(), clsName)
            except TypeError:
                pass

# end
Example #42
0
	def getFunctionCaller(depth: int = 3) -> str:
		return inspect.getmodulename(inspect.stack()[depth][1])
Example #43
0
def calling_function_qualified_name(depth=1):
    # type: (int) -> Optional[str]
    """
    >>> def my_function(): return calling_function_qualified_name()
    >>> print(my_function())
    my_function
    """

    if not isinstance(depth, int):

        depth_representation = repr(depth)

        raise TypeError(
            'The parameter `depth` for `serial.utilities.calling_function_qualified_name` must be an `int`, not' +
            (
                (':\n%s' if '\n' in depth_representation else ' %s.') %
                depth_representation
            )
        )

    stack = inspect.stack()

    if len(stack) < (depth + 1):

        return None

    else:

        name_list = []
        stack = inspect.stack()
        frame_info = stack[depth]  # type: inspect.FrameInfo

        try:
            frame_function = frame_info.function
        except AttributeError:
            frame_function = frame_info[3]

        if frame_function != '<module>':

            try:
                frame = frame_info.frame
            except AttributeError:
                frame = frame_info[0]

            name_list.append(frame_function)
            arguments, _, _, frame_locals = inspect.getargvalues(frame)

            if arguments:

                argument = arguments[0]
                argument_value = frame_locals[argument]
                argument_value_type = type(argument_value)

                if (
                    hasattr(argument_value_type, '__name__') and
                    hasattr(argument_value_type, '__module__') and
                    (
                        (argument_value_type.__name__ not in dir(builtins)) or
                        (getattr(builtins, argument_value_type.__name__) is not argument_value_type)
                    )
                ):
                    name_list.append(qualified_name(argument_value_type))

        if len(name_list) < 2:

            try:
                file_name = frame_info.filename
            except AttributeError:
                file_name = frame_info[1]

            module_name = inspect.getmodulename(file_name)

            if module_name not in sys.modules:

                path_parts = list(os.path.split(file_name))
                path_parts.pop()

                while path_parts:

                    parent = path_parts.pop()
                    module_name = parent + '.' + module_name

                    if module_name in sys.modules:
                        break

            if module_name is None:
                raise ValueError('The path "%s" is not a python module' % file_name)
            else:
                if module_name in sys.modules:
                    qualified_module_name = qualified_name(sys.modules[module_name])
                    name_list.append(qualified_module_name)
        return '.'.join(reversed(name_list))
Example #44
0
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))
Example #45
0
def serialize_parser_and_lexer():
    t = time.time()
    G.serialize_lexer('CoolLexer', inspect.getmodulename(__file__))
    G.serialize_parser('lalr1', 'CoolParser', inspect.getmodulename(__file__))
    print('Serialization Time :', time.time() - t, 'seconds')
Example #46
0
def doc_func(func=None, verbose=True):
    """(doc_func)...Documenting code using inspect

    Parameters
    ----------
    func : function
        Function name to document, without quotes
    verbose : Boolean
        True prints the result, False returns a string of the result.

    Returns
    -------
    A listing of the source code with line numbers

    Notes
    -----
    Requires the `inspect` module

    Source code for::

        module level
        - inspect.getsourcelines(sys.modules[__name__])[0]

        function level
        - as a list => inspect.getsourcelines(num_41)[0]
        - as a string => inspect.getsource(num_41)

        file level
        - script = sys.argv[0]

    """
    def demo_func():
        """dummy...
        : Demonstrates retrieving and documenting module and function info.
        """
        def sub():
            """sub in dummy"""
            print("sub")

        return None

    #
    import inspect
    if func is None:
        func = demo_func
    if not inspect.isfunction(func):
        out = "\nError... `{}` is not a function, but is of type... {}\n"
        print(out.format(func.__name__, type(func)))
        return None
    script2 = sys.argv[0]  # a useful way to get a file's name
    lines, line_num = inspect.getsourcelines(func)
    code = "".join([
        "{:4d}  {}".format(idx + line_num, line)
        for idx, line in enumerate(lines)
    ])
    nmes = [
        'args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults',
        'annotations'
    ]
    f = inspect.getfullargspec(func)
    f_args = "\n".join([str(i) for i in list(zip(nmes, list(f)))])
    args = [
        line_num, code,
        inspect.getcomments(func),
        inspect.isfunction(func),
        inspect.ismethod(func),
        inspect.getmodulename(script2), f_args
    ]
    frmt = """
    :----------------------------------------------------------------------
    :---- doc_func(func) ----
    :Code for a function on line...{}...
    :
    {}
    Comments preceeding function
    {}
    function?... {} ... or method? {}
    Module name... {}
    Full specs....
    {}
    ----------------------------------------------------------------------
    """
    out = (dedent(frmt)).format(*args)
    if verbose:
        print(out)
    else:
        return out
Example #47
0
 def getCallerMod(self, callLevel=2):
     fileName = inspect.stack()[callLevel][1]
     modName = inspect.getmodulename(fileName)
     return modName
Example #48
0
def set_hist(key_or_path,
             value,
             module_name='_auto_detect',
             kill=False,
             to_file=PLING_HISTORY_JSON):
    """ Write to "plugin history.json" one value by key or path (list of keys).
        If any of node doesnot exist it will be added.
        Or remove (if kill) one key+value pair (if suitable key exists).
        Parameters
            key_or_path     Key(s) to navigate in json tree
                            Type: str or [str]
            value           Value to set if suitable item in json tree exists
            module_name     Start node to navigate.
                            If it is '_auto_detect' then name of caller module is used.
                            If it is None then it is skipped.
            kill            Need to remove node in tree.
                            if kill==True parm value is ignored
            to_file         Name of file to write. APP_DIR_SETTING will be joined if no full path.
        
        Return              value (param)   if !kill and modification is successful
                            value (killed)  if  kill and modification is successful
                            None            if  kill and no path in tree (no changes)
                            KeyError        if !kill and path has problem
        Return  value
            
        Examples (caller module is 'plg')
        1. If no "plugin history.json"  it will become
            set_hist('k',0,None)        {"k":0}
            set_hist('k',1)             {"plg":{"k":1}}
            set_hist('k',1,'plg')       {"plg":{"k":1}}
            set_hist('k',1,'oth')       {"oth":{"k":1}}
            set_hist('k',[1,2])         {"plg":{"k":[1,2]}}
            set_hist(['p','k'], 1)      {"plg":{"p":{"k":1}}}
        
        2. If "plugin history.json" contains    {"plg":{"k":1, "p":{"m":2}}}
                                                it will contain
            set_hist('k',0,None)                {"plg":{"k":1, "p":{"m":2}},"k":0}
            set_hist('k',0)                     {"plg":{"k":0, "p":{"m":2}}}
            set_hist('k',0,'plg')               {"plg":{"k":0, "p":{"m":2}}}
            set_hist('n',3)                     {"plg":{"k":1, "p":{"m":2}, "n":3}}
            set_hist(['p','m'], 4)              {"plg":{"k":1, "p":{"m":4}}}
            set_hist('p',{'m':4})               {"plg":{"k":1, "p":{"m":4}}}
            set_hist(['p','m','k'], 1)          KeyError (old m is not branch node)

        3. If "plugin history.json" contains    {"plg":{"k":1, "p":{"m":2}}}
                                                it will contain
            set_hist('k',       kill=True)      {"plg":{       "p":{"m":2}}}
            set_hist('p',       kill=True)      {"plg":{"k":1}}
            set_hist(['p','m'], kill=True)      {"plg":{"k":1, "p":{}}}
            set_hist('n',       kill=True)      {"plg":{"k":1, "p":{"m":2}}}    (nothing to kill)
    """
    to_file = to_file if os.sep in to_file else app.app_path(
        app.APP_DIR_SETTINGS) + os.sep + to_file
    body    = json.loads(open(to_file).read(), object_pairs_hook=odict) \
                if os.path.exists(to_file) and os.path.getsize(to_file) != 0 else \
              odict()

    if module_name == '_auto_detect':
        caller_globals = inspect.stack()[1].frame.f_globals
        module_name = inspect.getmodulename(caller_globals['__file__']) \
                        if '__file__' in caller_globals else None
    keys = [key_or_path] if type(key_or_path) == str else key_or_path
    keys = keys if module_name is None else [module_name] + keys
    parents,\
    key     = keys[:-1], keys[-1]
    data = body
    for parent in parents:
        if kill and parent not in data:
            return None
        data = data.setdefault(parent, odict())
        if type(data) != odict:
            raise KeyError()
    if kill:
        if key not in data:
            return None
        value = data.pop(key)
    else:
        data[key] = value
    open(to_file, 'w').write(json.dumps(body, indent=2))
    return value
Example #49
0
    $$
    formula = %s_{%d}%s_{%d}
    $$
    $$
    formula \: weight = %.3f \: amu 
    $$
    </div>''' % (self.e1, self.p1, self.e1, self.e1, self.aw1, self.n1,
                 self.e1, self.e2, self.p2, self.e2, self.e2, self.aw2,
                 self.n2, self.e2, min(self.n1, self.n2), self.f, self.e1,
                 self.c1, self.e2, self.c2, self.wt)
        ]


if __name__ == '__main__':
    f = open('test.html', 'w')
    me = importlib.import_module(inspect.getmodulename(__file__))
    print me
    probs = [
        me.__dict__[k] for k in me.__dict__
        if type(me.__dict__[k]) == types.ClassType
    ]
    examples = [prob() for prob in probs]
    head = '''<!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">

    <title>%s</title>

    <style>
    #question {font-size: 20px; font-weight: bold;}
Example #50
0
def main():
    # Get testcases
    tests = os.listdir()
    i = 0
    # print(tests)
    # while i < len(tests):
    #     if not tests[i].startswith('test_'):
    #         tests.remove(tests[i])
    #     else:
    #         i+=1
    tests = removentests(tests)
    # print(tests)
    modules = []
    #print(os.getcwd())
    sys.path.insert(0, os.getcwd())
    for testf in tests:
        #print(testf)
        modules.append(importlib.import_module(inspect.getmodulename(testf)))
    # print(modules)
    testcases = []
    for module in modules:
        for testcase in inspect.getmembers(module, predicate=inspect.isclass):
            testcases.append(testcase[1])

    # Run testcases
    testcases_run = 0
    testcasesr = []
    tests_run = 0
    succeded = True
    for testcase in testcases:
        testcases_run += 1
        t = test_cases(testcase)
        fname = inspect.getfile(testcase)
        for test in t[2]:
            for assertion in test:
                failed = assertion[0] == 1
                lineno = assertion[1]
                if failed:
                    methodtests = removentests(inspect.getmembers(
                        testcase(), predicate=inspect.ismethod),
                                               f=False)
                    method = methodtests[t[2].index(test)]
                    #print(method)
                    print('')
                    print('\033[0m\033[1;30;41mFailed @ def', method[0] + '()',
                          'in class', testcase.__name__, 'in', fname,
                          '\033[0m')
                    print('')
                    print(get_lines_around(fname, lineno))
        tests_run += t[0]
        testcasesr.append(t[2])
        if t[1] == False:
            succeded = False
            break
    tstr = 'tests'
    if tests_run == 1:
        tstr = 'test'
    tcstr = 'testcases'
    if testcases_run == 1:
        tcstr = 'testcase'
    print('Ran ' + str(tests_run) + ' ' + tstr + ' in ' + str(testcases_run),
          tcstr)
    if succeded:
        print('')
        print('         \033[0m\033[1;30;42m                          \033[0m')
        print('         \033[0m\033[1;30;42m            OK            \033[0m')
        print('         \033[0m\033[1;30;42m                          \033[0m')
        print('')
        exit(0)
    else:
        print('')
        print('         \033[0m\033[1;30;41m                          \033[0m')
        print('         \033[0m\033[1;30;41m          Failed          \033[0m')
        print('         \033[0m\033[1;30;41m                          \033[0m')
        print('')
        exit(1)
 def start(self):
     return inspect.getmodulename(inspect.stack()[1][1])
Example #52
0
def get_current_module():
    module = inspect.getsourcefile(inspect.stack()[1][0])
    return inspect.getmodulename(module)
Example #53
0
    def docmodule(self,
                  object,
                  name=None,
                  mod=None,
                  packageContext=None,
                  *ignored):
        """Produce HTML documentation for a module object."""
        name = object.__name__  # ignore the passed-in name
        parts = split(name, '.')
        links = []
        for i in range(len(parts) - 1):
            links.append(
                '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
                (join(parts[:i + 1], '.'), parts[i]))
        linkedname = join(links + parts[-1:], '.')
        head = '<big><big><strong>%s</strong></big></big>' % linkedname
        try:
            path = inspect.getabsfile(object)
            url = path
            if sys.platform == 'win32':
                import nturl2path
                url = nturl2path.pathname2url(path)
            filelink = '<a href="file:%s">%s</a>' % (url, path)
        except TypeError:
            filelink = '(built-in)'
        info = []
        if hasattr(object, '__version__'):
            version = str(object.__version__)
            if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
                version = strip(version[11:-1])
            info.append('version %s' % self.escape(version))
        if hasattr(object, '__date__'):
            info.append(self.escape(str(object.__date__)))
        if info:
            head = head + ' (%s)' % join(info, ', ')
        result = self.heading(head, '#ffffff', '#7799ee',
                              '<a href=".">index</a><br>' + filelink)

        modules = inspect.getmembers(object, inspect.ismodule)

        classes, cdict = [], {}
        for key, value in inspect.getmembers(object, inspect.isclass):
            if (inspect.getmodule(value) or object) is object:
                classes.append((key, value))
                cdict[key] = cdict[value] = '#' + key
        for key, value in classes:
            for base in value.__bases__:
                key, modname = base.__name__, base.__module__
                module = sys.modules.get(modname)
                if modname != name and module and hasattr(module, key):
                    if getattr(module, key) is base:
                        if not cdict.has_key(key):
                            cdict[key] = cdict[base] = modname + '.html#' + key
        funcs, fdict = [], {}
        for key, value in inspect.getmembers(object, inspect.isroutine):
            if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
                funcs.append((key, value))
                fdict[key] = '#-' + key
                if inspect.isfunction(value): fdict[value] = fdict[key]
        data = []
        for key, value in inspect.getmembers(object, pydoc.isdata):
            if key not in ['__builtins__', '__doc__']:
                data.append((key, value))

        doc = self.markup(pydoc.getdoc(object), self.preformat, fdict, cdict)
        doc = doc and '<tt>%s</tt>' % doc
        result = result + '<p>%s</p>\n' % doc

        packageContext.clean(classes, object)
        packageContext.clean(funcs, object)
        packageContext.clean(data, object)

        if hasattr(object, '__path__'):
            modpkgs = []
            modnames = []
            for file in os.listdir(object.__path__[0]):
                path = os.path.join(object.__path__[0], file)
                modname = inspect.getmodulename(file)
                if modname and modname not in modnames:
                    modpkgs.append((modname, name, 0, 0))
                    modnames.append(modname)
                elif pydoc.ispackage(path):
                    modpkgs.append((file, name, 1, 0))
            modpkgs.sort()
            contents = self.multicolumn(modpkgs, self.modpkglink)
            ##			result = result + self.bigsection(
            ##				'Package Contents', '#ffffff', '#aa55cc', contents)
            result = result + self.moduleSection(object, packageContext)
        elif modules:
            contents = self.multicolumn(
                modules, lambda (key, value), s=self: s.modulelink(value))
            result = result + self.bigsection('Modules', '#fffff', '#aa55cc',
                                              contents)

        if classes:
            classlist = map(lambda (key, value): value, classes)
            contents = [
                self.formattree(inspect.getclasstree(classlist, 1), name)
            ]
            for key, value in classes:
                contents.append(self.document(value, key, name, fdict, cdict))
            result = result + self.bigsection('Classes', '#ffffff', '#ee77aa',
                                              join(contents))
        if funcs:
            contents = []
            for key, value in funcs:
                contents.append(self.document(value, key, name, fdict, cdict))
            result = result + self.bigsection('Functions', '#ffffff',
                                              '#eeaa77', join(contents))
        if data:
            contents = []
            for key, value in data:
                try:
                    contents.append(self.document(value, key))
                except Exception, err:
                    pass
            result = result + self.bigsection('Data', '#ffffff', '#55aa55',
                                              join(contents, '<br>\n'))
Example #54
0
 def wrapper(*args, **kwargs):
     for fr in inspect.stack():
         if inspect.getmodulename(fr[1]) in ('loaddata', 'sync_dev'):
             return
     signal_handler(*args, **kwargs)
import inspect
import json
import logging
from logging import DEBUG, INFO, WARNING, FATAL, ERROR
import sys

import yaml

from gridappsd import GridAPPSD
import fncs

_log = logging.getLogger(inspect.getmodulename(__file__))

DEFAULT_FNCS_LOCATION = 'tcp://localhost:5570'
DEFAULT_INPUT_TOPIC = '/topic/goss.gridappsd.simulation.input'
DEFAULT_OUTPUT_TOPIC = '/topic/goss.gridappsd.simulation.output'
BASE_SIMULATION_STATUS_TOPIC = "/topic/goss.gridappsd.process.log.simulation"


class GridAPPSDListener(object):
    def __init__(self, fncs_bridge, gridappsd):
        if not fncs_bridge:
            raise AttributeError("fncs_bridge must be set!")
        self._bridge = fncs_bridge
        self._gridappsd = gridappsd

    def on_message(self, headers, msg):
        message = {}
        try:
            message_str = 'received message ' + str(msg)
            if fncs.is_initialized():
Example #56
0
 def test_modules(self):
     self.assertEqual(
         inspect.getmodulename(
             '/Users/hexiaoan/PycharmProjects/PyRepository/src/builtIns/samples.py'
         ), 'samples')
Example #57
0
import sys
# 将上两级目录也就是advance_feature加入到sys.path中
sys.path.append(
    os.path.abspath(os.path.dirname(__file__) + os.path.sep + ".."))
from inspect_test.test2 import hello


class KevinTest():
    def __init__(self):
        print('i am eric huang')

    def say_hello(self, name):
        hello()
        return 'Hello {name}'.format(name=name)


if __name__ == "__main__":
    # 取到当前模块名
    print(inspect.getmodulename(__file__))

    # inspect.getmodule(object) 用来返回object定义在哪个module中
    print(inspect.getmodule(hello))

    # inspect.getfile(object)用来返回object定义在哪个 file 中。
    test = KevinTest()
    print(inspect.getfile(test.say_hello))

    # inspect.getmembers(object) 用来返回object的所有成员列表(为(name, value)的形式)。
    # 输出test里的所有是方法的成员变量。
    print(inspect.getmembers(test, inspect.ismethod))
Example #58
0
    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
    print "Mode\t:%s %s" % (mode, mode_description)
    print "Mtype\t:%s" % mtype_name

# Get Module name
module = inspect.getmodulename(filename)
print "Module %s" % module
Example #59
0
import inspect
import logging
import os
import tempfile
import shutil

# Third-party imports
import disdat.common
import disdat.resources
import disdat.utility.aws_s3 as aws
from disdat.infrastructure import dockerizer
from disdat.fs import determine_pipe_version

import docker

_MODULE_NAME = inspect.getmodulename(__file__)

_DOCKERIZER_ROOT = os.path.dirname(inspect.getsourcefile(dockerizer))

_logger = logging.getLogger(__name__)


def _copy_in_dot_file(disdat_config, docker_context, dot_file_name,
                      option_name, cli):
    """
    Copy in a dot file to a file with name "dot_file_name" into the docker context.
    The user might have put the src path in the disdat config file under the "option_name"

    Args:
        disdat_config:  A disdat config object
        docker_context:  The place we are storing the docker context for build
Example #60
0
def get_hist(key_or_path,
             default=None,
             module_name='_auto_detect',
             to_file=PLING_HISTORY_JSON):
    """ Read from "plugin history.json" one value by string key or path (list of keys).
        Parameters
            key_or_path     Key(s) to navigate in json tree
                            Type: str or [str]
            default         Value to return  if no suitable node in json tree
            module_name     Start node to navigate.
                            If it is '_auto_detect' then name of caller module is used.
                            If it is None then it is skipped.
            to_file         Name of file to read. APP_DIR_SETTING will be joined if no full path.
        
        Return              Found value or default
            
        Examples (caller module is 'plg')
        1. If no "plugin history.json"
                get_hist('k')                   returns None
                get_hist(['p', 'k'], 0)         returns 0
        2. If "plugin history.json" contains 
                {"k":1, "plg":{"k":2, "p":{"m":3}, "t":[0,1]}, "q":{"n":4}}
                get_hist('k', 0, None)          returns 1
                get_hist('k', 0)                returns 0
                get_hist('k', 0, 'plg')         returns 2
                get_hist('k', 0, 'oth')         returns 0
                get_hist(['p','m'], 0)          returns 3
                get_hist(['p','t'], [])         returns [0,1]
                get_hist('q', 0, None)          returns {'n':4}
                get_hist(['q','n'], 0, None)    returns 4
    """
    to_file = to_file if os.sep in to_file else app.app_path(
        app.APP_DIR_SETTINGS) + os.sep + to_file
    if not os.path.exists(to_file):
        pass
        #log('not exists',())
        return default
    data = None
    try:
        data = json.loads(open(to_file).read())
    except:
        pass
        log('not load: {}', sys.exc_info())
        return default
    if module_name == '_auto_detect':
        caller_globals = inspect.stack()[1].frame.f_globals
        module_name = inspect.getmodulename(caller_globals['__file__']) \
                        if '__file__' in caller_globals else None
        pass
        #log('module_name={}',(module_name))
    keys = [key_or_path] if type(key_or_path) == str else key_or_path
    keys = keys if module_name is None else [module_name] + keys
    parents,\
    key     = keys[:-1], keys[-1]
    for parent in parents:
        data = data.get(parent)
        if type(data) != dict:
            pass
            #log('not dict parent={}',(parent))
            return default
    return data.get(key, default)