本文整理匯總了Python中inspect.getfile方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.getfile方法的具體用法?Python inspect.getfile怎麽用?Python inspect.getfile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.getfile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: traceback_response
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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)
示例2: test_ppFact_fits
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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__)
示例3: test_FAdMag0_fits
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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__)
示例4: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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')
示例5: loadAliasFile
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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
##########################################################
示例6: test_static_blueprint_name
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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
示例7: read_file
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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()
示例8: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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
示例9: _getfile
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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)
示例10: initUI
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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')
#####################################################################
示例11: main
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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)
示例12: get_tests
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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
示例13: get_tests
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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
示例14: _ModelParamsClassKey
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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__)
示例15: get_config_comments
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfile [as 別名]
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