Python __main__.__file__() Examples
The following are 30
code examples of __main__.__file__().
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
__main__
, or try the search function
.
Example #1
Source File: juanita.py From esoteric-python-challenges with GNU General Public License v3.0 | 6 votes |
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
Example #2
Source File: common.py From pytorch-revnet with MIT License | 6 votes |
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)
Example #3
Source File: util.py From rtrl with MIT License | 6 votes |
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 ====================================================================================================
Example #4
Source File: juanita.py From esoteric-python-challenges with GNU General Public License v3.0 | 6 votes |
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)
Example #5
Source File: util.py From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal | 6 votes |
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 )
Example #6
Source File: test_package.py From citest with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: util.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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 )
Example #8
Source File: rumps.py From Tautulli with GNU General Public License v3.0 | 6 votes |
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
Example #9
Source File: application.py From presto-admin with Apache License 2.0 | 5 votes |
def __main_module_path(self): return os.path.abspath(main.__file__)
Example #10
Source File: utils.py From neptune-client with Apache License 2.0 | 5 votes |
def discover_git_repo_location(): # pylint:disable=bad-option-value,import-outside-toplevel import __main__ if hasattr(__main__, '__file__'): return os.path.dirname(os.path.abspath(__main__.__file__)) return None
Example #11
Source File: rop_generator.py From EasyROP with GNU General Public License v3.0 | 5 votes |
def parse_rop_file(self, file): ret = [] try: for op in [line.rstrip('\n') for line in open(file)]: ret += [self.parse_op(op)] except (FileNotFoundError, UnicodeDecodeError, IsADirectoryError): print("%s: '%s': Not a plain text file" % (os.path.basename(__main__.__file__), os.path.realpath(file))) raise FileNotFoundError return ret
Example #12
Source File: test_runner_test.py From citest with Apache License 2.0 | 5 votes |
def test_main(self): """Test citest.base.TestRunner.main() invocation.""" global in_test_main test_fixtures = [TestRunnerTest, TestParamFixture, TestBindingsFixture] argv = sys.argv old_config = os.environ.get('CITEST_CONFIG_PATH') os.environ['CITEST_CONFIG_PATH'] = os.path.join( os.path.dirname(__file__), 'bindings_test.config') try: in_test_main = True sys.argv = [sys.argv[0], '--test_binding', 'MyTestBindingValue', '--test_param', 'MyTestParamValue'] result = TestingTestRunner.main(test_case_list=test_fixtures) finally: in_test_main = False sys.argv = argv if old_config: os.environ['CITEST_CONFIG_PATH'] = old_config else: del os.environ['CITEST_CONFIG_PATH'] self.assertEqual(0, result) self.assertEqual(call_check, test_fixtures) self.assertEqual(1, TestingTestRunner.terminate_calls)
Example #13
Source File: test_runner_test.py From citest with Apache License 2.0 | 5 votes |
def test_init_bindings_builder(self): """Verify the builtin bindings.""" builder = ConfigurationBindingsBuilder() TestRunner.global_runner().init_bindings_builder(builder) bindings = builder.build() self.assertEqual('.', bindings.get('log_dir')) self.assertEqual(os.path.splitext(os.path.basename(__main__.__file__))[0], bindings.get('log_filebase')) # While not necessarily a design criteria, the implementation has all # the bindings added by all the fixtures. self.assertEqual('MyTestParamValue', bindings.get('TEST_PARAM')) self.assertEqual('MyTestBindingValue', bindings.get('TEST_BINDING'))
Example #14
Source File: rop_generator.py From EasyROP with GNU General Public License v3.0 | 5 votes |
def parse_op(self, op): try: match = re.search(r'^([a-zA-Z0-9_\-]+)\(([a-zA-Z0-9,_\- ]*)\)$', op) op_parsed = match.group(1) reg1, reg2 = self.parse_operands(match.group(2)) except AttributeError: print("%s: '%s': Compile error, must be like 'operation(reg1, reg2)', 'operation(reg1)' or 'operation()'" % (os.path.basename(__main__.__file__), op)) raise return {"original": op, "op": op_parsed, "dst": reg1, "src": reg2}
Example #15
Source File: parser.py From EasyROP with GNU General Public License v3.0 | 5 votes |
def get_operation(self, op): try: return self._file.get_operation(op) except ParseException: ops = self._file.get_all_ops() ops.sort() string = ", ".join(ops) print("%s: '%s': Can not find op between: %s" % (os.path.basename(__main__.__file__), op, string)) raise
Example #16
Source File: args.py From EasyROP with GNU General Public License v3.0 | 5 votes |
def check_args(self): if self._args.binary: self.check_files(self._args.binary) if self._args.op: self.parser.get_operation(self._args.op) if self._args.reg_dst is not None and self._args.reg_dst not in REGISTERS_X86: print("%s: '%s': Not a valid register" % (os.path.basename(__main__.__file__), self._args.reg_dst)) sys.exit(-1) if self._args.reg_src is not None and self._args.reg_src not in REGISTERS_X86: print("%s: '%s': Not a valid register" % (os.path.basename(__main__.__file__), self._args.reg_src)) sys.exit(-1)
Example #17
Source File: args.py From EasyROP with GNU General Public License v3.0 | 5 votes |
def check_files(self, binaries): for binary in binaries: file = Path(binary) if not file.is_file(): print("%s: '%s': Not a file" % (os.path.basename(__main__.__file__), os.path.realpath(binary))) raise FileNotFoundError
Example #18
Source File: metrics.py From pipeline with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setup_metrics(host="localhost", name=None): """Setup metric generation. Use dotted namespaces e.g. "pipeline.centrifugation" """ if name is None: import __main__ prefix = splitext(basename(__main__.__file__))[0] else: prefix = name prefix = prefix.strip(".") return statsd.StatsClient(host, 8125, prefix=prefix)
Example #19
Source File: metrics.py From pipeline with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setup_metrics(host="localhost", name=None): """Setup metric generation. Use dotted namespaces e.g. "pipeline.centrifugation" """ if name is None: import __main__ prefix = splitext(basename(__main__.__file__))[0] else: prefix = name prefix = prefix.strip(".") return statsd.StatsClient(host, 8125, prefix=prefix)
Example #20
Source File: metrics.py From pipeline with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setup_metrics(host="localhost", name=None): """Setup metric generation. Use dotted namespaces e.g. "pipeline.centrifugation" """ if name is None: import __main__ prefix = splitext(basename(__main__.__file__))[0] else: prefix = name prefix = prefix.strip(".") return statsd.StatsClient(host, 8125, prefix=prefix)
Example #21
Source File: metrics.py From pipeline with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setup_metrics(host="localhost", name=None): """Setup metric generation. Use dotted namespaces e.g. "pipeline.centrifugation" """ if name is None: import __main__ prefix = splitext(basename(__main__.__file__))[0] else: prefix = name prefix = prefix.strip(".") return statsd.StatsClient(host, 8125, prefix=prefix)
Example #22
Source File: runner.py From win-unicode-console with MIT License | 5 votes |
def run_script(args): sys.argv = [args.script] + args.script_arguments path = args.script __main__.__file__ = path try: code = get_code(path) except Exception as e: traceback.print_exception(e.__class__, e, None, file=sys.stderr) else: try: exec(code, __main__.__dict__) except BaseException as e: if not sys.flags.inspect and isinstance(e, SystemExit): raise elif PY2: # Python 2 produces tracebacks in mixed encoding (!) etype, e, tb = sys.exc_info() for line in traceback.format_exception(etype, e, tb.tb_next): line = line.decode("utf-8", "replace") try: sys.stderr.write(line) except UnicodeEncodeError: line = line.encode(sys.stderr.encoding, "backslashreplace") sys.stderr.write(line) sys.stderr.flush() # is this needed? else: # PY3 traceback.print_exception(e.__class__, e, e.__traceback__.tb_next, file=sys.stderr)
Example #23
Source File: ca_certs_locater.py From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal | 5 votes |
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)
Example #24
Source File: ca_certs_locater.py From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal | 5 votes |
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
Example #25
Source File: module_finder_test.py From mitogen with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_main(self): import __main__ path, source, is_pkg = self.call('__main__') self.assertTrue(path is not None) self.assertTrue(os.path.exists(path)) self.assertEquals(path, __main__.__file__) fp = open(path, 'rb') try: self.assertEquals(source, fp.read()) finally: fp.close() self.assertFalse(is_pkg)
Example #26
Source File: module_finder_test.py From mitogen with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_main(self): import __main__ path, src, is_pkg = self.call('__main__') self.assertEquals(path, __main__.__file__) # linecache adds a line ending to the final line if one is missing. actual_src = open(path, 'rb').read() if actual_src[-1:] != b('\n'): actual_src += b('\n') self.assertEquals(src, actual_src) self.assertFalse(is_pkg)
Example #27
Source File: utils.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
def get_diagnostics_info(): # TODO(gsamfira): decide if we want any other kind of # diagnostics. packages = list(freeze.freeze()) return { "application": os.path.basename(main.__file__), "packages": packages, "os_info": _get_host_os_info(), "hostname": platform.node(), "ip_addresses": _get_local_ips(), }
Example #28
Source File: utils.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
def get_resources_dir(): return os.path.join( os.path.dirname(os.path.abspath(__file__)), "resources")
Example #29
Source File: rumps.py From ComicStreamer with Apache License 2.0 | 5 votes |
def _nsimage_from_file(filename, dimensions=None): """ Takes a path to an image file and returns an NSImage object. """ try: _log('attempting to open image at {}'.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 {}'.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) return image # Decorators and helper function serving to register functions for dealing with interaction and events #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Example #30
Source File: View.py From spyre with MIT License | 5 votes |
def __init__(self): self.ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) self.JS_PATH = os.path.join(self.ROOT_DIR, 'public', 'js') self.CSS_PATH = os.path.join(self.ROOT_DIR, 'public', 'css') self.APP_PATH = os.path.dirname(os.path.realpath(__main__.__file__))