本文整理汇总了Python中__main__.__file__方法的典型用法代码示例。如果您正苦于以下问题:Python __main__.__file__方法的具体用法?Python __main__.__file__怎么用?Python __main__.__file__使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类__main__
的用法示例。
在下文中一共展示了__main__.__file__方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_base_app_name
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def get_base_app_name():
"""
Base App name, which this script belongs to.
"""
import __main__
main_name = __main__.__file__
absolute_path = os.path.normpath(main_name)
parts = absolute_path.split(os.path.sep)
parts.reverse()
for key in ("apps", "slave-apps", "master-apps"):
try:
idx = parts.index(key)
if parts[idx + 1] == "etc":
return parts[idx - 1]
except (ValueError, IndexError):
pass
raise RestError(
status=500,
message='Cannot get app name from file: %s' % main_name
)
示例2: download_file
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def download_file(url, binary=True):
if sys.version_info < (3,):
from urlparse import urlsplit
import urllib2
request = urllib2
error = urllib2
else:
from urllib.parse import urlsplit
from urllib import request, error
filename = os.path.basename(urlsplit(url)[2])
data_dir = os.path.join(os.path.dirname(__file__), 'data')
path = os.path.join(data_dir, filename)
if os.path.exists(path):
return path
try:
data = request.urlopen(url, timeout=15).read()
with open(path, 'wb' if binary else 'w') as f:
f.write(data)
return path
except error.URLError:
msg = "could not download test file '{}'".format(url)
warnings.warn(msg, RuntimeWarning)
raise unittest.SkipTest(msg)
示例3: git_info
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def git_info(path=None):
"""returns a dict with information about the git repo at path (path can be a sub-directory of the git repo)
"""
import __main__
path = path or os.path.dirname(__main__.__file__)
rev = get_output('git rev-parse HEAD'.split(), cwd=path)
count = int(get_output('git rev-list HEAD --count'.split(), cwd=path, default=-1))
status = get_output('git status --short'.split(), cwd=path) # shows un-committed modified files
commit_date = get_output("git show --quiet --date=format-local:%Y-%m-%dT%H:%M:%SZ --format=%cd".split(), cwd=path, env=dict(TZ='UTC'))
desc = get_output(['git', 'describe', '--long', '--tags', '--dirty', '--always', '--match', r'v[0-9]*\.[0-9]*'], cwd=path)
message = desc + " " + ' '.join(get_output(['git', 'log', '--oneline', '--format=%B', '-n', '1', "HEAD"], cwd=path).splitlines())
url = get_output('git config --get remote.origin.url'.split(), cwd=path).strip()
# if on github, change remote to a meaningful https url
if url.startswith('git@github.com:'):
url = 'https://github.com/' + url[len('git@github.com:'):-len('.git')] + '/commit/' + rev
elif url.startswith('https://github.com'):
url = url[:len('.git')] + '/commit/' + rev
return dict(url=url, rev=rev, count=count, status=status, desc=desc, date=commit_date, message=message)
# === serialization ====================================================================================================
示例4: _mock_syntax_error
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def _mock_syntax_error(message, line_no):
"""
Output an error which is visually similar to a regular
SyntaxError. This will refer to a line in the main script.
"""
# fetch the exact erroneous line of the script.
with open(__main__.__file__) as script:
for line in range(line_no - 1):
script.readline()
error_line = script.readline().strip()
sys.stderr.write(textwrap.dedent(f"""\
File "{__main__.__file__}", line {line_no}
{error_line}
SyntaxError: {message}
"""))
sys.exit(1)
示例5: _maybify_main_script
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def _maybify_main_script():
"""Do all the sorcery. Implements Maybe for __main__."""
try:
source = inspect.getsource(__main__)
except TypeError:
raise RuntimeError(
"unable to set up Maybe. are you in a REPL?"
) from None
main_code = compile(source, __main__.__file__, "exec")
patched_module = _implement_maybe(main_code)
# now run the new shit as if nothing ever happened :D
exec(patched_module)
exit(0) # stop the *actual* module from running afterwards tho
示例6: run_all_tests_in_dir
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def run_all_tests_in_dir(dirname=None, recurse=False):
"""Run all the *_test.py files in the provided directory.
Args:
dirname: Path to directory containing tests. If not defined, use the
directory that the __main__.__file__ is in.
recurse: True if should recurse the directory tree for all the tests.
"""
if not dirname:
dirname = os.path.dirname(__main__.__file__) or '.'
if recurse:
# pylint: disable=unused-variable
suites = []
for walk_dir, file_list, dir_list in os.walk(dirname):
suites.extend(collect_suites_in_dir(walk_dir))
else:
suites = collect_suites_in_dir(dirname)
test_suite = unittest.TestSuite(suites)
runner = TestRunner(runner=unittest.TextTestRunner(verbosity=2))
return runner.run(test_suite)
示例7: _nsimage_from_file
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def _nsimage_from_file(filename, dimensions=None, template=None):
"""Take a path to an image file and return an NSImage object."""
try:
_log('attempting to open image at {0}'.format(filename))
with open(filename):
pass
except IOError: # literal file path didn't work -- try to locate image based on main script path
try:
from __main__ import __file__ as main_script_path
main_script_path = os.path.dirname(main_script_path)
filename = os.path.join(main_script_path, filename)
except ImportError:
pass
_log('attempting (again) to open image at {0}'.format(filename))
with open(filename): # file doesn't exist
pass # otherwise silently errors in NSImage which isn't helpful for debugging
image = NSImage.alloc().initByReferencingFile_(filename)
image.setScalesWhenResized_(True)
image.setSize_((20, 20) if dimensions is None else dimensions)
if not template is None:
image.setTemplate_(template)
return image
示例8: _read_httplib2_default_certs
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def _read_httplib2_default_certs():
import httplib2 # import error should not happen here, and will be well handled by outer called
httplib_dir = os.path.dirname(os.path.abspath(httplib2.__file__))
ca_certs_path = os.path.join(httplib_dir, HTTPLIB2_CA_CERT_FILE_NAME)
return _read_pem_file(ca_certs_path)
示例9: _get_temp_cert_file_dir
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def _get_temp_cert_file_dir():
import __main__
app_root = op.dirname(op.dirname(op.abspath(__main__.__file__)))
temp_dir = op.join(app_root, 'temp_certs')
if not op.isdir(temp_dir):
try:
os.mkdir(temp_dir)
except:
pass
for candidate in ['temp_certs', 'local', 'default']:
dir_path = op.join(app_root, candidate)
if op.isdir(dir_path):
return dir_path
return app_root
示例10: __init__
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def __init__(self, fn,
handler=None,
file_end_handler=None,
exclusive=True,
id=None,
strip=False,
read_chunk_size=read_size):
self.fn = fn
self.handler = handler
self.file_end_handler = file_end_handler
self.exclusive = exclusive
if id is None:
if hasattr(__main__, '__file__'):
id = __main__.__file__
id = os.path.basename(id)
if id == '<stdin>':
id = '__stdin__'
else:
id = '__instant_command__'
self.id = id
self.strip = strip
read_chunk_size = int(read_chunk_size)
if read_chunk_size <= 0:
read_chunk_size = read_size
self.read_chunk_size = read_chunk_size
self.running = None
self.bufferred = None # (offset, content)
if (self.handler is not None
and callable(self.handler)):
self.handler = [self.handler]
示例11: get_root_log_fn
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def get_root_log_fn():
if hasattr(__main__, '__file__'):
name = __main__.__file__
name = os.path.basename(name)
if name == '<stdin>':
name = '__stdin__'
return name.rsplit('.', 1)[0] + '.' + log_suffix
else:
return '__instant_command__.' + log_suffix
示例12: _default_pid_file
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def _default_pid_file():
if hasattr(__main__, '__file__'):
name = __main__.__file__
name = os.path.basename(name)
if name == '<stdin>':
name = '__stdin__'
return '/var/run/' + name.rsplit('.', 1)[0]
else:
return '/var/run/pykit.daemonize'
示例13: autodiscover_version
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def autodiscover_version(caller_filename=None, save_to=None, max_parent_depth=None):
""" walk back along the path to the current module, searching for a VERSION file """
if not caller_filename:
caller_filename = os.path.realpath(__file__)
file_path = os.path.abspath(os.path.dirname(caller_filename))
cur_path = file_path
while True:
version_fn = os.path.join(cur_path, "VERSION")
if os.path.exists(version_fn):
version = open(version_fn, "rt").readline().strip()
if save_to:
f = open(os.path.join(file_path, save_to), "wt")
f.write("# This file is autogenerated. Do not edit.\n")
f.write("__version__ = '%s'\n" % version)
f.close()
return version
# limit_parent_depth can be used to limit how far back we search the tree for a VERSION file.
if max_parent_depth is not None:
if max_parent_depth <= 0:
return None
max_parent_depth -= 1
(cur_path, remainder) = os.path.split(cur_path)
if not remainder:
return None
示例14: autodiscover_version_of_caller
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def autodiscover_version_of_caller(*args, **kwargs):
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
return autodiscover_version(module.__file__, *args, **kwargs)
示例15: autodiscover_version_of_main
# 需要导入模块: import __main__ [as 别名]
# 或者: from __main__ import __file__ [as 别名]
def autodiscover_version_of_main(*args, **kwargs):
import __main__
if hasattr(__main__, "__file__"):
return autodiscover_version(__main__.__file__, *args, **kwargs)
else:
return None