Python inspect.getfile() Examples

The following are 30 code examples of inspect.getfile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: debug.py    From quart with MIT License 7 votes vote down vote up
def traceback_response() -> Response:
    type_, value, tb = sys.exc_info()
    frames = []
    while tb:
        frame = tb.tb_frame
        try:
            code = inspect.getsourcelines(frame)
        except OSError:
            code = None

        frames.append(
            {
                "file": inspect.getfile(frame),
                "line": frame.f_lineno,
                "locals": frame.f_locals,
                "code": code,
            }
        )
        tb = tb.tb_next

    name = type_.__name__
    template = Template(TEMPLATE)
    html = template.render(frames=reversed(frames), name=name, value=value)
    return Response(html, 500) 
Example #2
Source File: test_blueprints.py    From sanic with MIT License 6 votes vote down vote up
def test_static_blueprint_name(app: Sanic, static_file_directory, file_name):
    current_file = inspect.getfile(inspect.currentframe())
    with open(current_file, "rb") as file:
        file.read()

    bp = Blueprint(name="static", url_prefix="/static", strict_slashes=False)

    bp.static(
        "/test.file/",
        get_file_path(static_file_directory, file_name),
        name="static.testing",
        strict_slashes=True,
    )

    app.blueprint(bp)

    uri = app.url_for("static", name="static.testing")
    assert uri == "/static/test.file"

    _, response = app.test_client.get("/static/test.file")
    assert response.status == 404

    _, response = app.test_client.get("/static/test.file/")
    assert response.status == 200 
Example #3
Source File: TargetList.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def loadAliasFile(self):
        """
        Args:
        Returns:
            alias ():
                list 
        """
        #OLD aliasname = 'alias_4_11_2019.pkl'
        aliasname = 'alias_10_07_2019.pkl'
        tmp1 = inspect.getfile(self.__class__).split('/')[:-2]
        tmp1.append('util')
        self.classpath = '/'.join(tmp1)
        #self.classpath = os.path.split(inspect.getfile(self.__class__))[0]
        #vprint(inspect.getfile(self.__class__))
        self.alias_datapath = os.path.join(self.classpath, aliasname)
        #Load pkl and outspec files
        try:
            with open(self.alias_datapath, 'rb') as f:#load from cache
                alias = pickle.load(f, encoding='latin1')
        except:
            vprint('Failed to open fullPathPKL %s'%self.alias_datapath)
            pass
        return alias
    ########################################################## 
Example #4
Source File: SIMBAD300Catalog.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, cachedir=None, **specs):
        self.cachedir = get_cache_dir(cachedir)
        classpath = os.path.split(inspect.getfile(self.__class__))[0]
        filename = 'SIMBAD300'
        pklpath = os.path.join(self.cachedir, filename + '.pkl')
        matpath = os.path.join(classpath, filename + '.mat')
        
        # check if given filename exists as .pkl file already
        if os.path.exists(pklpath):
            self.populatepkl(pklpath, **specs)
            self.vprint('Loaded %s.pkl star catalog'%filename)
        # check if given filename exists as a .mat file but not .pkl file
        elif os.path.exists(matpath):
            self.SIMBAD_mat2pkl(matpath, pklpath)
            self.populatepkl(pklpath, **specs)
            self.vprint('Loaded %s.mat star catalog'%filename)
        # otherwise print error
        else:
            self.vprint('Could not load SIMBAD300 star catalog') 
Example #5
Source File: test_PostProcessing.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_FAdMag0_fits(self):
        # get fits file path for FAdMag0 test
        classpath = os.path.split(inspect.getfile(self.__class__))[0]
        FAdMag0Path = os.path.join(classpath,'test_PostProcessing_FAdMag0.fits')

        # fits file has values for WA in [0.1, 0.2] and FAdMag0 in [10, 20]
        testWA = np.linspace(0.1, 0.2, 100)*u.arcsec

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(FAdMag0=FAdMag0Path,**self.specs)

            vals = obj.FAdMag0(testWA)

            self.assertTrue(np.all(vals >= 10),'value below range of FAdMag0 for %s'%mod.__name__)
            self.assertTrue(np.all(vals <= 20),'value above range of FAdMag0 for %s'%mod.__name__) 
Example #6
Source File: test_PostProcessing.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ppFact_fits(self):
        # get fits file path for ppFact test
        classpath = os.path.split(inspect.getfile(self.__class__))[0]
        ppFactPath = os.path.join(classpath,'test_PostProcessing_ppFact.fits')

        # fits file has values for WA in [0.1,0.2]
        testWA = np.linspace(0.1,0.2,100)*u.arcsec

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(ppFact=ppFactPath,**self.specs)

            vals = obj.ppFact(testWA)

            self.assertTrue(np.all(vals > 0),'negative value of ppFact for %s'%mod.__name__)
            self.assertTrue(np.all(vals <= 1),'ppFact > 1 for %s'%mod.__name__) 
Example #7
Source File: functions.py    From chainer-compiler with MIT License 6 votes vote down vote up
def __init__(self, func):
        super().__init__()

        self.inst = func
        self.name = func.__name__
        self.filename = inspect.getfile(func)
        sourcelines = inspect.getsourcelines(func)
        self.lineno = sourcelines[1]
        self.args.analyze_args(func)

        if (func.__name__ == (lambda: None).__name__):
            original_code = utils.lambda_source(func)
            code = 'return ' + original_code[re.search('lambda.*?:', original_code).end():]
            self.ast = gast.ast_to_gast(ast.parse(code))
        else:
            original_code = inspect.getsource(func)
            code = utils.clip_head(original_code)
            ast_ = gast.ast_to_gast(ast.parse(code)).body[0]
            self.ast = canonicalizer.Canonicalizer().visit(ast_) 
Example #8
Source File: test_plugin.py    From atomic-reactor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_check_no_reload(caplog, tmpdir, docker_tasker):
    """
    test if plugins are not reloaded
    """
    workflow = mock_workflow(tmpdir)
    this_file = inspect.getfile(MyBsPlugin1)
    expected_log_message = "load file '%s'" % this_file
    BuildStepPluginsRunner(docker_tasker,
                           workflow,
                           [{"name": "MyBsPlugin1"}],
                           plugin_files=[this_file])
    assert any(expected_log_message in l.getMessage() for l in caplog.records)
    log_len = len(caplog.records)
    BuildStepPluginsRunner(docker_tasker,
                           workflow,
                           [{"name": "MyBsPlugin1"}],
                           plugin_files=[this_file])
    assert all(expected_log_message not in l.getMessage() for l in caplog.records[log_len:]) 
Example #9
Source File: resource_loader.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def get_path_to_datafile(path):
  """Get the path to the specified file in the data dependencies.

  The path is relative to tensorflow/

  Args:
    path: a string resource path relative to tensorflow/

  Returns:
    The path to the specified file present in the data attribute of py_test
    or py_binary.

  Raises:
    IOError: If the path is not found, or the resource can't be opened.
  """
  data_files_path = _os.path.dirname(_inspect.getfile(_sys._getframe(1)))
  return _os.path.join(data_files_path, path) 
Example #10
Source File: dispatcher.py    From spore with MIT License 6 votes vote down vote up
def global_reload():
    """ filter all loaded spore modules in the script dir and
    reload each of them. this is a convenience function for developing """

    import inspect

    windowed = mel.eval('$temp1=$gMainWindow')
    if windowed:
        scripts_dir = os.path.dirname(__file__)
        for key, module in sys.modules.iteritems():

            try:
                module_path = inspect.getfile(module)
            except TypeError:
                continue

            if module_path == __file__:
                continue

            if module_path.startswith(scripts_dir):
                reload(module) 
Example #11
Source File: utils.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def read_file(filename, depth=1):
    """reads the file"""

    if not filename:
        raise ValueError("filename not supplied")

    # Expanding filename
    filename = os.path.expanduser(filename)
    file_path = os.path.join(
        os.path.dirname(inspect.getfile(sys._getframe(depth))), filename
    )

    if not file_exists(file_path):
        LOG.debug("file {} not found at location {}".format(filename, file_path))
        raise ValueError("file {} not found".format(filename))

    with open(file_path, "r") as data:
        return data.read() 
Example #12
Source File: tbtools.py    From recruit with Apache License 2.0 6 votes vote down vote up
def __init__(self, exc_type, exc_value, tb):
        self.lineno = tb.tb_lineno
        self.function_name = tb.tb_frame.f_code.co_name
        self.locals = tb.tb_frame.f_locals
        self.globals = tb.tb_frame.f_globals

        fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
        if fn[-4:] in (".pyo", ".pyc"):
            fn = fn[:-1]
        # if it's a file on the file system resolve the real filename.
        if os.path.isfile(fn):
            fn = os.path.realpath(fn)
        self.filename = to_unicode(fn, get_filesystem_encoding())
        self.module = self.globals.get("__name__")
        self.loader = self.globals.get("__loader__")
        self.code = tb.tb_frame.f_code

        # support for paste's traceback extensions
        self.hide = self.locals.get("__traceback_hide__", False)
        info = self.locals.get("__traceback_info__")
        if info is not None:
            info = to_unicode(info, "utf-8", "replace")
        self.info = info 
Example #13
Source File: obspy.py    From pyweed with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _getfile(object):
    """
    Override inspect.getfile

    A common idiom within Obspy to get a file path of the current code
    (eg. to find a data file in the same package) is
    >>> inspect.getfile(inspect.currentframe())
    This doesn't work in PyInstaller for some reason.

    In every case I've tried, this returns the same thing as __file__,
    which does work in PyInstaller, so this hook tries to return that instead.
    """
    if inspect.isframe(object):
        try:
            file = object.f_globals['__file__']
            # print("inspect.getfile returning %s" % file)
            return file
        except:
            pass
    return _old_getfile(object) 
Example #14
Source File: virtual_joystick.py    From differential-drive with GNU General Public License v3.0 6 votes vote down vote up
def initUI(self):      
    #####################################################################    
        
        img_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/../images/crosshair.jpg"
        rospy.loginfo("initUI img_path: %s" % img_path)

        self.statusBar()
        
        self.setStyleSheet("QMainWindow { border-image: url(%s); }" % img_path)
        
                
        self.setGeometry(0, 600, 200, 200)
        self.setWindowTitle('Virtual Joystick')
        self.show()
        self.timer = QtCore.QBasicTimer()
        
        self.statusBar().showMessage('started')
        
    ##################################################################### 
Example #15
Source File: setup.py    From peony-twitter with MIT License 6 votes vote down vote up
def main():
    if sys.version_info < (3, 5, 3):
        raise RuntimeError("Peony requires Python 3.5.3+")

    dirname = os.path.dirname(inspect.getfile(inspect.currentframe()))

    # get metadata and keywords from peony/__init__.py
    kwargs = get_metadata(os.path.join(dirname, 'peony', '__init__.py'))

    # get requirements from requirements.txt
    kwargs.update(get_requirements(os.path.join(dirname, 'requirements.txt')))

    # get extras requirements from extras_require.txt
    extras = os.path.join(dirname, 'extras_require.txt')
    extras_require = get_requirements(extras)

    # get long description from README.md
    with open('README.rst') as stream:
        long_description = stream.read()

    setup(long_description=long_description,
          packages=find_packages(include=["peony*"]),
          extras_require=extras_require,
          python_requires='>=3.5.3',
          **kwargs) 
Example #16
Source File: test_DSA.py    From earthengine with MIT License 6 votes vote down vote up
def get_tests(config={}):
    tests = []
    tests += list_test_cases(DSATest)
    try:
        from Crypto.PublicKey import _fastmath
        tests += list_test_cases(DSAFastMathTest)
    except ImportError:
        from distutils.sysconfig import get_config_var
        import inspect
        _fm_path = os.path.normpath(os.path.dirname(os.path.abspath(
            inspect.getfile(inspect.currentframe())))
            +"/../../PublicKey/_fastmath"+get_config_var("SO"))
        if os.path.exists(_fm_path):
            raise ImportError("While the _fastmath module exists, importing "+
                "it failed. This may point to the gmp or mpir shared library "+
                "not being in the path. _fastmath was found at "+_fm_path)
    tests += list_test_cases(DSASlowMathTest)
    return tests 
Example #17
Source File: test_RSA.py    From earthengine with MIT License 6 votes vote down vote up
def get_tests(config={}):
    tests = []
    tests += list_test_cases(RSATest)
    try:
        from Crypto.PublicKey import _fastmath
        tests += list_test_cases(RSAFastMathTest)
    except ImportError:
        from distutils.sysconfig import get_config_var
        import inspect
        _fm_path = os.path.normpath(os.path.dirname(os.path.abspath(
            inspect.getfile(inspect.currentframe())))
            +"/../../PublicKey/_fastmath"+get_config_var("SO"))
        if os.path.exists(_fm_path):
            raise ImportError("While the _fastmath module exists, importing "+
                "it failed. This may point to the gmp or mpir shared library "+
                "not being in the path. _fastmath was found at "+_fm_path)
    if config.get('slow_tests',1):
        tests += list_test_cases(RSASlowMathTest)
    return tests 
Example #18
Source File: model_registry.py    From lingvo with Apache License 2.0 6 votes vote down vote up
def _ModelParamsClassKey(cls, src_cls):
    """Returns a string key used for `src_cls` in the model registry.

    The returned key is a period separated string. E.g., image.mnist.LeNet5. It
    roughly reflects how params files are organized. We put some of the
    directory information into the key to avoid future model name conflicts.

    Args:
      src_cls: A subclass of `~.base_model.BaseModel`.
    """
    path = src_cls.__module__
    # Removes the prefix.
    path_prefix = cls._ClassPathPrefix()
    path = path.replace(path_prefix, '')

    # Removes 'params.' if exists.
    if 'params.' in path:
      path = path.replace('params.', '')
    if inspect.getfile(src_cls).endswith('test.py'):
      return 'test.{}'.format(src_cls.__name__)
    return '{}.{}'.format(path, src_cls.__name__) 
Example #19
Source File: config_scope.py    From sacred with MIT License 6 votes vote down vote up
def get_config_comments(func):
    filename = inspect.getfile(func)
    func_body, line_offset = get_function_body(func)
    body_source = dedent_function_body(func_body)
    body_code = compile(body_source, filename, "exec", ast.PyCF_ONLY_AST)
    body_lines = body_source.split("\n")

    variables = {"seed": "the random seed for this experiment"}

    for ast_root in body_code.body:
        for ast_entry in [ast_root] + list(ast.iter_child_nodes(ast_root)):
            if isinstance(ast_entry, ast.Assign):
                # we found an assignment statement
                # go through all targets of the assignment
                # usually a single entry, but can be more for statements like:
                # a = b = 5
                for t in ast_entry.targets:
                    add_doc(t, variables, body_lines)

    return variables 
Example #20
Source File: compat.py    From python-netsurv with MIT License 5 votes vote down vote up
def getlocation(function, curdir):
    function = get_real_func(function)
    fn = py.path.local(inspect.getfile(function))
    lineno = function.__code__.co_firstlineno
    if fn.relto(curdir):
        fn = fn.relto(curdir)
    return "%s:%d" % (fn, lineno + 1) 
Example #21
Source File: source.py    From python-netsurv with MIT License 5 votes vote down vote up
def getfslineno(obj):
    """ Return source location (path, lineno) for the given object.
    If the source cannot be determined return ("", -1)
    """
    try:
        code = py.code.Code(obj)
    except TypeError:
        try:
            fn = (inspect.getsourcefile(obj) or
                  inspect.getfile(obj))
        except TypeError:
            return "", -1

        fspath = fn and py.path.local(fn) or None
        lineno = -1
        if fspath:
            try:
                _, lineno = findsource(obj)
            except IOError:
                pass
    else:
        fspath = code.path
        lineno = code.firstlineno
    assert isinstance(lineno, int)
    return fspath, lineno

#
# helper functions
# 
Example #22
Source File: source.py    From python-netsurv with MIT License 5 votes vote down vote up
def getfslineno(obj):
    """ Return source location (path, lineno) for the given object.
    If the source cannot be determined return ("", -1).

    The line number is 0-based.
    """
    from .code import Code

    try:
        code = Code(obj)
    except TypeError:
        try:
            fn = inspect.getsourcefile(obj) or inspect.getfile(obj)
        except TypeError:
            return "", -1

        fspath = fn and py.path.local(fn) or None
        lineno = -1
        if fspath:
            try:
                _, lineno = findsource(obj)
            except IOError:
                pass
    else:
        fspath = code.path
        lineno = code.firstlineno
    assert isinstance(lineno, int)
    return fspath, lineno


#
# helper functions
# 
Example #23
Source File: mlbv.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def display_usage():
    """Displays contents of readme file."""
    current_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
    readme_path = os.path.abspath(os.path.join(current_dir, '..', 'README.md'))
    if not os.path.exists(readme_path):
        print("Could not find documentation file [expected at: {}]".format(readme_path))
        return -1
    if 'PAGER' in os.environ:
        cmd = [os.environ['PAGER'], readme_path]
        subprocess.run(cmd)
    else:
        with open(readme_path, 'r') as infile:
            for line in infile:
                print(line, end='')
    return 0 
Example #24
Source File: py_func.py    From ocelot with GNU General Public License v3.0 5 votes vote down vote up
def loc_class(obj):
    '''
    locates the file where class of the object is defined
    '''
    print(inspect.getfile(obj.__class__)) 
Example #25
Source File: compat.py    From python-netsurv with MIT License 5 votes vote down vote up
def getlocation(function, curdir):
    function = get_real_func(function)
    fn = py.path.local(inspect.getfile(function))
    lineno = function.__code__.co_firstlineno
    if fn.relto(curdir):
        fn = fn.relto(curdir)
    return "%s:%d" % (fn, lineno + 1) 
Example #26
Source File: finders.py    From python-netsurv with MIT License 5 votes vote down vote up
def _load_mapping():
        """Return list of mappings `package_name -> module_name`

        Example:
            django-haystack -> haystack
        """
        if not pipreqs:
            return
        path = os.path.dirname(inspect.getfile(pipreqs))
        path = os.path.join(path, 'mapping')
        with open(path) as f:
            # pypi_name: import_name
            return dict(line.strip().split(":")[::-1] for line in f) 
Example #27
Source File: testutils.py    From pygcode with GNU General Public License v3.0 5 votes vote down vote up
def add_pygcode_to_path():
    global _pygcode_in_path
    if not _pygcode_in_path:
        if os.environ.get('PYGCODE_TESTSCOPE', 'local') == 'installed':
            # Run tests on the `pip install` installed libray
            pass  # nothing to be done
        else:
            # Run tests explicitly on files in ../src (ignore any installed libs)
            # Add pygcode (relative to this test-path) to the system path
            _this_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
            sys.path.insert(0, os.path.join(_this_path, '..', 'src'))

        _pygcode_in_path = True 
Example #28
Source File: op.py    From D-VAE with MIT License 5 votes vote down vote up
def get_path(cls, f):
        """
        Convert a path relative to the location of the class file into
        an aboslute path. Paths that are already absolute are passed
        through unchanged.

        """
        if not os.path.isabs(f):
            class_file = inspect.getfile(cls)
            class_dir = os.path.dirname(class_file)
            f = os.path.realpath(os.path.join(class_dir, f))
        return f 
Example #29
Source File: runner.py    From TestSlide with MIT License 5 votes vote down vote up
def _dsl_print(self, example, description, code):
        if not self.dsl_debug:
            return
        name = code.__name__
        try:
            file = inspect.getsourcefile(code)
        except TypeError:
            try:
                file = inspect.getfile(code)
            except TypeError:
                file = "?"
        if file.startswith(os.path.dirname(__file__)):
            return
        if self.trim_path_prefix:
            split = file.split(self.trim_path_prefix)
            if len(split) == 2 and not split[0]:
                file = split[1]
        try:
            _lines, lineno = inspect.getsourcelines(code)
        except OSError:
            lineno = "?"
        self.print_cyan(
            "{indent}{description}: {name} @ {file_lineno}".format(
                indent=self.get_dsl_debug_indent(example),
                description=description,
                name=name,
                file_lineno=f"{file}:{lineno}",
            )
        ) 
Example #30
Source File: source.py    From python-netsurv with MIT License 5 votes vote down vote up
def getfslineno(obj):
    """ Return source location (path, lineno) for the given object.
    If the source cannot be determined return ("", -1)
    """
    try:
        code = py.code.Code(obj)
    except TypeError:
        try:
            fn = (inspect.getsourcefile(obj) or
                  inspect.getfile(obj))
        except TypeError:
            return "", -1

        fspath = fn and py.path.local(fn) or None
        lineno = -1
        if fspath:
            try:
                _, lineno = findsource(obj)
            except IOError:
                pass
    else:
        fspath = code.path
        lineno = code.firstlineno
    assert isinstance(lineno, int)
    return fspath, lineno

#
# helper functions
#