我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getabsfile()。
def script_dir(pyobject, follow_symlinks=True): """Get current script's directory Args: pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True. Returns: str: Current script's directory """ if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = abspath(sys.executable) else: path = inspect.getabsfile(pyobject) if follow_symlinks: path = realpath(path) return dirname(path)
def register(self, match, func, flags=0, mention=False, admin=False, channel_id='*'): logger.debug('Registering message: %s, %s from %s', match, func.__name__, inspect.getabsfile(func)) if not asyncio.iscoroutinefunction(func): func = asyncio.coroutine(func) option = { 'func': func, 'mention': mention, 'admin': admin, 'channel_id': channel_id } self._endpoints[re.compile(match, flags)].append(option)
def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "http://docs.python.org/library") basedir = os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator
def get_script_dir(follow_symlinks=True): if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = abspath(sys.executable) else: path = inspect.getabsfile(get_script_dir) if follow_symlinks: path = realpath(path) return dirname(path)
def get_script_dir(follow_symlinks=True) : if getattr(sys, 'frozen', False) : path = os.path.abspath(sys.executable) else : path = inspect.getabsfile(get_script_dir) if follow_symlinks : path = os.path.realpath(path) return os.path.dirname(path) # https://stackoverflow.com/a/781074
def get_script_dir(follow_symlinks=True): if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = os.path.abspath(sys.executable) else: path = inspect.getabsfile(get_script_dir) if follow_symlinks: path = os.path.realpath(path) return os.path.dirname(path).replace("\\", "/")
def do_inspect(self, arg): obj = self._getval(arg) data = OrderedDict() data['Type'] = type(obj).__name__ data['String Form'] = str(obj).strip() try: data['Length'] = len(obj) except TypeError: pass try: data['File'] = inspect.getabsfile(obj) except TypeError: pass if (isinstance(obj, type) and hasattr(obj, '__init__') and getattr(obj, '__module__') != '__builtin__'): # Class - show definition and docstring for constructor data['Docstring'] = obj.__doc__ data['Constructor information'] = '' try: data[' Definition'] = '%s%s' % (arg, signature(obj)) except ValueError: pass data[' Docstring'] = obj.__init__.__doc__ else: try: data['Definition'] = '%s%s' % (arg, signature(obj)) except (TypeError, ValueError): pass data['Docstring'] = obj.__doc__ for key, value in data.items(): formatted_key = Color.set(Color.red, key + ':') self.stdout.write('%-28s %s\n' % (formatted_key, value))
def _get_position_of_arg(self, arg): try: obj = self._getval(arg) except: return None, None, None if isinstance(obj, str): return obj, 1, None try: filename = inspect.getabsfile(obj) lines, lineno = inspect.getsourcelines(obj) except (IOError, TypeError) as e: print('** Error: %s **' % e, file=self.stdout) return None, None, None return filename, lineno, lines
def _setup_blueprint(self, module_name, module_ref): root_dir = os.path.dirname(inspect.getabsfile(module_ref)) kwargs = {} # Register templates template_folder = os.path.join(root_dir, 'templates') if os.path.isdir(template_folder): kwargs.update({'template_folder': 'templates'}) # Register static files, if any static_folder = os.path.join(root_dir, 'static') if os.path.isdir(static_folder): kwargs.update({ 'static_folder': 'static', 'static_url_path': '/static/plugins/{}'.format(module_name) }) # Generate blueprint blueprint = flask.Blueprint(module_name, module_name, **kwargs) # Add the plugin_static() helper function to the # template context @blueprint.context_processor def static_processor(): def plugin_static(filename): return flask.url_for('{}.static'.format(module_name), filename=filename) return dict(plugin_static=plugin_static) # Blueprint done, return it return blueprint
def find_file(obj): """Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absolute path to the file where the object was defined. """ obj = _get_wrapped(obj) fname = None try: fname = inspect.getabsfile(obj) except TypeError: # For an instance, the file that matters is where its class was # declared. if hasattr(obj, '__class__'): try: fname = inspect.getabsfile(obj.__class__) except TypeError: # Can happen for builtins pass except: pass return cast_unicode(fname)
def test_html_doc(self): result, doc_loc = get_pydoc_html(pydoc_mod) mod_file = inspect.getabsfile(pydoc_mod) if sys.platform == 'win32': import nturl2path mod_url = nturl2path.pathname2url(mod_file) else: mod_url = mod_file expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc) if result != expected_html: print_diffs(expected_html, result) self.fail("outputs are not equal, see diff above")
def test_text_doc(self): result, doc_loc = get_pydoc_text(pydoc_mod) expected_text = expected_text_pattern % \ (doc_loc, inspect.getabsfile(pydoc_mod)) if result != expected_text: print_diffs(expected_text, result) self.fail("outputs are not equal, see diff above")
def test_help_output_redirect(self): # issue 940286, if output is set in Helper, then all output from # Helper.help should be redirected old_pattern = expected_text_pattern getpager_old = pydoc.getpager getpager_new = lambda: (lambda x: x) self.maxDiff = None buf = StringIO() helper = pydoc.Helper(output=buf) unused, doc_loc = get_pydoc_text(pydoc_mod) module = "test.pydoc_mod" help_header = """ Help on module test.pydoc_mod in test: """.lstrip() help_header = textwrap.dedent(help_header) expected_help_pattern = help_header + expected_text_pattern pydoc.getpager = getpager_new try: with captured_output('stdout') as output, \ captured_output('stderr') as err: helper.help(module) result = buf.getvalue().strip() expected_text = expected_help_pattern % \ (doc_loc, inspect.getabsfile(pydoc_mod)) self.assertEqual('', output.getvalue()) self.assertEqual('', err.getvalue()) self.assertEqual(expected_text, result) finally: pydoc.getpager = getpager_old
def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS) basedir = os.path.join(sys.exec_prefix, "lib", "python%d.%d" % sys.version_info[:2]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', '_thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator
def test_html_doc(self): result, doc_loc = get_pydoc_html(pydoc_mod) mod_file = inspect.getabsfile(pydoc_mod) if sys.platform == 'win32': import nturl2path mod_url = nturl2path.pathname2url(mod_file) else: mod_url = mod_file expected_html = expected_html_pattern % ( (mod_url, mod_file, doc_loc) + expected_html_data_docstrings) if result != expected_html: print_diffs(expected_html, result) self.fail("outputs are not equal, see diff above")
def test_text_doc(self): result, doc_loc = get_pydoc_text(pydoc_mod) expected_text = expected_text_pattern % ( (inspect.getabsfile(pydoc_mod), doc_loc) + expected_text_data_docstrings) if result != expected_text: print_diffs(expected_text, result) self.fail("outputs are not equal, see diff above")
def getdocloc(self, object, basedir=os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3])): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "https://docs.python.org/library") basedir = os.path.normcase(basedir) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith(("http://", "https://")): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower()) else: docloc = os.path.join(docloc, object.__name__.lower() + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator
def test_text_doc(self): result, doc_loc = get_pydoc_text(pydoc_mod) expected_text = expected_text_pattern % ( (doc_loc,) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod),)) if result != expected_text: print_diffs(expected_text, result) self.fail("outputs are not equal, see diff above")
def test_help_output_redirect(self): # issue 940286, if output is set in Helper, then all output from # Helper.help should be redirected old_pattern = expected_text_pattern getpager_old = pydoc.getpager getpager_new = lambda: (lambda x: x) self.maxDiff = None buf = StringIO() helper = pydoc.Helper(output=buf) unused, doc_loc = get_pydoc_text(pydoc_mod) module = "test.pydoc_mod" help_header = """ Help on module test.pydoc_mod in test: """.lstrip() help_header = textwrap.dedent(help_header) expected_help_pattern = help_header + expected_text_pattern pydoc.getpager = getpager_new try: with captured_output('stdout') as output, \ captured_output('stderr') as err: helper.help(module) result = buf.getvalue().strip() expected_text = expected_help_pattern % ( (doc_loc,) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod),)) self.assertEqual('', output.getvalue()) self.assertEqual('', err.getvalue()) self.assertEqual(expected_text, result) finally: pydoc.getpager = getpager_old
def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS) basedir = os.path.join(sys.base_exec_prefix, "lib", "python%d.%d" % sys.version_info[:2]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', '_thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator
def register(self, command, func): logger.debug('Registering slash command: %s, %s from %s', command, func.__name__, inspect.getabsfile(func)) if not asyncio.iscoroutinefunction(func): func = asyncio.coroutine(func) self._endpoints[command] = func
def register(self, event, func): logger.debug('Registering event: %s, %s from %s', event, func.__name__, inspect.getabsfile(func)) if not asyncio.iscoroutinefunction(func): func = asyncio.coroutine(func) self._endpoints[event].append(func)
def register(self, id_, func, public=False): logger.debug('Registering action: %s, %s from %s', id_, func.__name__, inspect.getabsfile(func)) if not asyncio.iscoroutinefunction(func): func = asyncio.coroutine(func) settings = {'func': func, 'public': public} self._endpoints[id_] = settings
def main(): explicit = False if len(sys.argv) == 2: explicit = True srctree = os.path.abspath(sys.argv[1]) else: srctree = os.path.dirname(inspect.getabsfile(c7n)) update_headers(srctree) if not explicit: update_headers(os.path.abspath('tests')) update_headers(os.path.abspath('ftests'))
def get_script_dir(follow_symlinks=True): if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = os.path.abspath(sys.executable) else: path = inspect.getabsfile(get_script_dir) if follow_symlinks: path = os.path.realpath(path) return os.path.dirname(path)
def test_html_doc(self): result, doc_loc = get_pydoc_html(pydoc_mod) mod_file = inspect.getabsfile(pydoc_mod) mod_url = urllib.parse.quote(mod_file) expected_html = expected_html_pattern % ( (mod_url, mod_file, doc_loc) + expected_html_data_docstrings) if result != expected_html: print_diffs(expected_html, result) self.fail("outputs are not equal, see diff above")
def find_file(obj): """Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absolute path to the file where the object was defined. """ # get source if obj was decorated with @decorator if safe_hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ fname = None try: fname = inspect.getabsfile(obj) except TypeError: # For an instance, the file that matters is where its class was # declared. if hasattr(obj, '__class__'): try: fname = inspect.getabsfile(obj.__class__) except TypeError: # Can happen for builtins pass except: # pylint:disable=bare-except pass return cast_unicode(fname)
def warnAboutFunction(offender, warningString): """ Issue a warning string, identifying C{offender} as the responsible code. This function is used to deprecate some behavior of a function. It differs from L{warnings.warn} in that it is not limited to deprecating the behavior of a function currently on the call stack. @param function: The function that is being deprecated. @param warningString: The string that should be emitted by this warning. @type warningString: C{str} @since: 11.0 """ # inspect.getmodule() is attractive, but somewhat # broken in Python < 2.6. See Python bug 4845. offenderModule = sys.modules[offender.__module__] filename = inspect.getabsfile(offenderModule) lineStarts = list(findlinestarts(offender.__code__)) lastLineNo = lineStarts[-1][1] globals = offender.__globals__ kwargs = dict( category=DeprecationWarning, filename=filename, lineno=lastLineNo, module=offenderModule.__name__, registry=globals.setdefault("__warningregistry__", {}), module_globals=None) warn_explicit(warningString, **kwargs)