コード例 #1
1
ファイル: runpy2.py プロジェクト: CxAalto/verkko
def main(argv=None):
    """Simulate 'python -m <modname>'.

    This is like the ``runpy`` standard library module, but this
    allows chained -m invocations.

    argv: The argv of the program, default sys.argv

        argv

    Some notes:
    'python -m somemodule' =>
        argv[0]=the module calling this
    'python -m somemodule' arg =>
        argv[0]=module calling this
        argv[1]=arg
    """
    if argv is None:
        import sys
        argv = sys.argv

    print argv
    del argv[0] # The script calling this.

    if len(argv) > 0 and argv[0] == '-m':
        modname = argv[1]
        del argv[0:1]
        runpy.run_module(modname, run_name='__main__', alter_sys=True)
    elif len(argv) > 0:
        runpy.run_path(argv[0], run_name='__main__')

    else:
        from code import interact
        interact(local={'__name__':'__main__'})
コード例 #2
0
ファイル: build.py プロジェクト: lecnim/stado
    def build_site(self, site: 'site directory'):
        """Returns imported site.py module from site directory."""

        path = os.path.join(os.getcwd(), site)

        # Create default site as a shortcut.
        # Now you can directly import: "from stado import run, before"
        default_site(path)

        if not os.path.exists(path):
            raise CommandError('Failed to build, site not found: ' + path)

        if self.is_site(path):

            log.info('Building site {}...'.format(site))
            timer = utils.Timer()

            # Run site.py
            script_path = os.path.join(path, 'site.py')

            try:
                runpy.run_path(script_path)
            except FileNotFoundError:
               raise CommandError('Failed to build, file not found: ' + script_path)

            log.info("Done! Site built in {}s".format(timer.get()))

        else:
            log.info('Failed to build, file site.py not found in '
                     'directory: {}'.format(site))

        clear_default_site()
コード例 #3
0
def main():
    if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
        stderr("usage: trace.py scriptfile [arg] ...")
        sys.exit(2)

    filename = sys.argv[1]     # Get script filename
    if not os.path.exists(filename):
        stderr('Error:', filename, 'does not exist')
        sys.exit(1)

    del sys.argv[0]         # Hide "trace.py" from argument list

    # Replace pdb's dir with script's dir in front of module search path.
    sys.path[0] = os.path.dirname(filename)

    globs = {
        "__name__": "__main__",
        "__file__": filename,
        "__builtins__": __builtins__,
    }

    sys.excepthook = _exception_handler

    runpy.run_path(
        filename,
        init_globals=globs,
        run_name='__main__')
コード例 #4
0
ファイル: apython.py プロジェクト: vxgmichel/apython
def run_apython(args=None):
    if args is None:
        args = sys.argv[1:]
    namespace = parse_args(args)

    try:
        sys._argv = sys.argv
        sys._path = sys.path
        if namespace.module:
            sys.argv = [None] + namespace.args
            sys.path.insert(0, '')
            events.set_interactive_policy(namespace.serve)
            runpy.run_module(namespace.filename,
                             run_name='__main__',
                             alter_sys=True)
        elif namespace.filename:
            sys.argv = [None] + namespace.args
            path = os.path.dirname(os.path.abspath(namespace.filename))
            sys.path.insert(0, path)
            events.set_interactive_policy(namespace.serve)
            runpy.run_path(namespace.filename,
                           run_name='__main__')
        else:
            events.run_console(serve=namespace.serve)
    finally:
        sys.argv = sys._argv
        sys.path = sys._path
コード例 #5
0
ファイル: sasview.py プロジェクト: rprospero/sasview
def run_cli():
    from multiprocessing import freeze_support
    freeze_support()
    setup_logging()
    # Use default matplotlib backend on mac/linux, but wx on windows.
    # The problem on mac is that the wx backend requires pythonw.  On windows
    # we are sure to wx since it is the shipped with the app.
    setup_mpl(backend='WXAgg' if os.name == 'nt' else None)
    setup_sasmodels()
    if len(sys.argv) == 1 or sys.argv[1] == '-i':
        # Run sasview as an interactive python interpreter
        try:
            from IPython import start_ipython
            sys.argv = ["ipython", "--pylab"]
            sys.exit(start_ipython())
        except ImportError:
            import code
            code.interact(local={'exit': sys.exit})
    elif sys.argv[1] == '-c':
        exec(sys.argv[2])
    else:
        thing_to_run = sys.argv[1]
        sys.argv = sys.argv[1:]
        import runpy
        if os.path.exists(thing_to_run):
            runpy.run_path(thing_to_run, run_name="__main__")
        else:
            runpy.run_module(thing_to_run, run_name="__main__")
コード例 #6
0
ファイル: runner.py プロジェクト: lookslikeawesome/japronto
def run(attribute, args):
    if args.script:
        runpy.run_path(attribute)
    else:
        attribute._run(
            host=args.host, port=args.port,
            worker_num=args.worker_num, reloader_pid=args.reloader_pid)
コード例 #7
0
ファイル: budget.py プロジェクト: PeterJCLaw/tools
    def _load_from_py(self, fname):
        with open(fname, "r") as in_file:
            in_src = in_file.read()

        if six.PY3:
            tempfile = NamedTemporaryFile('w', encoding='utf-8')
        else:
            tempfile = NamedTemporaryFile('w')

        with tempfile as f:
            trans_src = py_translate_to_decimals(in_src)
            f.write(trans_src)
            f.flush()

            conf = runpy.run_path(f.name,
                                  init_globals={"Decimal": D,
                                                "ceil": dec_ceil,
                                                "ceiling": dec_ceil,
                                                "floor": dec_floor})

        # Variables that are part of the normal running environment
        nullset = set(runpy.run_path("/dev/null").keys())

        # Remove vars that are part of the normal running env
        for name in nullset:
            if name in conf:
                conf.pop(name)

        self.vars = conf

        for vname in list(self.vars.keys()):
            val = self.vars[vname]
            if type(val) not in [int, D, float]:
                self.vars.pop(vname)
コード例 #8
0
ファイル: runtests.py プロジェクト: zachsnyder1/signalhook
	def make_test_data(self):
		"""
		The test/makeTestData/ directory contains two types of files.
		The first is a python script, whose name begins with 'make',
		and the other is a .csv file with the same name minus the 'make'.
		The makeTestData() function runs the __main__ within each of the
		python scripts, which in turn creates audio files for use in
		automated testing based on parameters in the corresponding .csv
		file.  The audio files are stored in the test/testdata directory.
		"""
		# make testData dir if necessary
		testDataPath = os.path.normpath(
						os.path.dirname(
						os.path.abspath(__file__)) + self.testDataDir)
		if not os.path.isdir(testDataPath):
			os.mkdir(testDataPath)
		else:
			for file in os.listdir(testDataPath):
				os.remove(os.path.join(testDataPath, file))
		# next make test data
		makeTestDataDirPath = os.path.dirname(
								os.path.abspath(__file__)) + \
								self.makeTestDataDir
		for file in os.listdir(makeTestDataDirPath):
			if file.startswith(self.makeScriptPrefix):
				runpy.run_path(makeTestDataDirPath + file, 
								run_name=self.runpyRunName)
			else:
				pass
コード例 #9
0
ファイル: __main__.py プロジェクト: lxhope/vmprof-python
def main():
    args = vmprof.cli.parse_args(sys.argv[1:])

    if args.web:
        output_mode = OUTPUT_WEB
    elif args.output:
        output_mode = OUTPUT_FILE
    else:
        output_mode = OUTPUT_CLI

    if output_mode == OUTPUT_FILE:
        prof_file = args.output
        prof_name = prof_file.name
    else:
        prof_file = tempfile.NamedTemporaryFile(delete=False)
        prof_name = prof_file.name

    vmprof.enable(prof_file.fileno(), args.period, args.mem)

    try:
        sys.argv = [args.program] + args.args
        sys.path.insert(0, os.path.dirname(args.program))
        runpy.run_path(args.program, run_name='__main__')
    except BaseException as e:
        if not isinstance(e, (KeyboardInterrupt, SystemExit)):
            raise
    vmprof.disable()
    prof_file.close()
    show_stats(prof_name, output_mode, args)
    if output_mode != OUTPUT_FILE:
        os.unlink(prof_name)
コード例 #10
0
ファイル: _lib.py プロジェクト: mpi4py/mpi4py
def import_main(mod_name, mod_path, init_globals, run_name):
    # pylint: disable=protected-access
    import types
    import runpy

    module = types.ModuleType(run_name)
    if init_globals is not None:
        module.__dict__.update(init_globals)
        module.__name__ = run_name

    class TempModulePatch(runpy._TempModule):
        # pylint: disable=too-few-public-methods
        def __init__(self, mod_name):
            # pylint: disable=no-member
            super(TempModulePatch, self).__init__(mod_name)
            assert self.module.__name__ == run_name
            self.module = module

    TempModule = runpy._TempModule  # pylint: disable=invalid-name
    runpy._TempModule = TempModulePatch
    import_main.sentinel = (mod_name, mod_path)
    try:
        main_module = sys.modules['__main__']
        sys.modules['__main__'] = sys.modules[run_name] = module
        if mod_name:  # pragma: no cover
            runpy.run_module(mod_name, run_name=run_name, alter_sys=True)
        elif mod_path:  # pragma: no branch
            runpy.run_path(mod_path, run_name=run_name)
        sys.modules['__main__'] = sys.modules[run_name] = module
    except:  # pragma: no cover
        sys.modules['__main__'] = main_module
        raise
    finally:
        del import_main.sentinel
        runpy._TempModule = TempModule
コード例 #11
0
ファイル: main.py プロジェクト: RanzQ/hyperion-audio-effects
def run_effect(effect='effect'):
    """
    Runs the module effect. Copy any hyperion effect code in this module or
    create your own. Note that effects that call hyperion.setImage(img) are
    not supported by the local gui, use hypersim instead.
    """
    runpy.run_path("effects/" + effect +'.py')
コード例 #12
0
ファイル: setup_py.py プロジェクト: neostoic/pydep
def setup_info(setupfile):
    """Returns metadata for a PyPI package by running its setupfile"""
    setup_dict = {}
    def setup_replacement(**kw):
        for k, v in kw.iteritems():
            setup_dict[k] = v

    setuptools_mod = __import__('setuptools')
    import distutils.core # for some reason, __import__('distutils.core') doesn't work

    # Mod setup()
    old_setuptools_setup = setuptools_mod.setup
    setuptools_mod.setup = setup_replacement
    old_distutils_setup = distutils.core.setup
    distutils.core.setup = setup_replacement
    # Mod sys.path (changing sys.path is necessary in addition to changing the working dir, because of Python's import resolution order)
    old_sys_path = list(sys.path)
    sys.path.insert(0, path.dirname(setupfile))
    # Change working dir (necessary because some setup.py files read relative paths from the filesystem)
    old_wd = os.getcwd()
    os.chdir(path.dirname(setupfile))

    runpy.run_path(path.basename(setupfile), run_name='__main__')

    # Restore working dir
    os.chdir(old_wd)
    # Restore sys.path
    sys.path = old_sys_path
    # Restore setup()
    distutils.core.setup = old_distutils_setup
    setuptools_mod.setup = old_setuptools_setup

    return setup_dict
コード例 #13
0
ファイル: __init__.py プロジェクト: mwilliamson/farthing
def _generate_trace(argv, trace_paths):
    with runtime.override_argv(argv):
        transformer = FunctionTraceTransformer(_trace_func_name)
        finder = importing.Finder(trace_paths, transformer)
        with runtime.prioritise_module_finder(finder):
            trace = []
            
            def trace_func(func_index):
                source_path, func = transformer.funcs[func_index]
                frame = sys._getframe(1)
                
                location = create_location(source_path, func.lineno, func.col_offset)
                entry = _trace_entry(location, func, frame)
                trace.append(entry)
                return _FunctionTracer(entry)
            
            def _farthing_assign_func_index(func_index):
                def assign(func):
                    func._farthing_func_index = func_index
                    return func
                    
                return assign
                
            extra_builtins = {
                _trace_func_name: trace_func,
                "_farthing_assign_func_index": _farthing_assign_func_index,
            }
            with runtime.add_builtins(extra_builtins):
                try:
                    runpy.run_path(argv[0], run_name="__main__")
                except:
                    # Swallow any errors
                    print(traceback.format_exc(), file=sys.stderr)
    
    return trace
コード例 #14
0
ファイル: test_version.py プロジェクト: jbremer/mitmproxy
def test_version(capsys):
    here = pathlib.Path(__file__).absolute().parent
    version_file = here / ".." / ".." / "mitmproxy" / "version.py"
    runpy.run_path(str(version_file), run_name='__main__')
    stdout, stderr = capsys.readouterr()
    assert len(stdout) > 0
    assert stdout.strip() == version.VERSION
コード例 #15
0
	def run(self):
		if os.path.isfile(self.path):
			runpy.run_path(self.path, init_globals=None, run_name=UI_RUN__NAME__)
			logger.info("UI "+self.name+" fermée")
		else:
			logger.error("L'ui "+self.path+" est introuvable")
		self.callback.onEnd(self.name)
コード例 #16
0
ファイル: __main__.py プロジェクト: cloax/pytrace
def main():
    pop_self_from_argv()
    if len(sys.argv) == 0:
        reader_main()
    else:
        with trace_context():
            runpy.run_path(sys.argv[0], run_name='__main__')
コード例 #17
0
ファイル: __main__.py プロジェクト: arigo/vmprof-python
def main():
    args = vmprof.cli.parse_args(sys.argv[1:])

    if args.web:
        output_mode = OUTPUT_WEB
    elif args.output:
        output_mode = OUTPUT_FILE
    else:
        output_mode = OUTPUT_CLI

    if output_mode == OUTPUT_FILE:
        prof_file = args.output
    else:
        prof_file = tempfile.NamedTemporaryFile()

    vmprof.enable(prof_file.fileno(), args.period)

    try:
        sys.argv = [args.program] + args.args
        runpy.run_path(args.program, run_name='__main__')
    except BaseException as e:
        if not isinstance(e, (KeyboardInterrupt, SystemExit)):
            raise
    vmprof.disable()
    show_stats(prof_file.name, output_mode, args)
コード例 #18
0
ファイル: wrap.py プロジェクト: vitaminmoo/unnaturalcode
def main():
    
    print sys.path
    
    name_err_extract = re.compile(r"^name\s+'([^']+)'")
    
    def get_file_line(filename, line):
    	try:
    		with open(filename) as f:
    			return filename.readlines()[line - 1]
    	except:
    		return None
    
    try:
    	runpy.run_path(sys.argv[1])
    except SyntaxError as se:
    	print 'syntax error: {} {}:{}'.format(se.filename, se.lineno - 1,
    		se.offset)
    except NameError as ne:
    	exctype, _, tb = sys.exc_info()
    	filename, line, func, text = traceback.extract_tb(tb)[-1]
    	name = name_err_extract.match(ne.message).group(1)
    	# note: text has all leading whitespace stripped, so the column
    	# we find for name will not be quite right.
    	column = (get_file_line(filename, line) or text).index(name)
    	print 'name error: {} {}:{}'.format(filename, line, column)
    
    print [m.__file__ for m in sys.modules.values() if hasattr(m, '__file__')] + [sys.argv[1]]
コード例 #19
0
ファイル: __init__.py プロジェクト: canonical-ols/talisker
def run():
    """Initialise Talisker then run python script."""
    initialise()
    logger = logging.getLogger('talisker.run')

    name = sys.argv[0]
    if '__main__.py' in name:
        # friendlier message
        name = '{} -m talisker'.format(sys.executable)

    extra = {}
    try:
        if len(sys.argv) < 2:
            raise RunException('usage: {} <script>  ...'.format(name))

        script = sys.argv[1]
        extra['script'] = script

        # pretend we just invoked 'python script.py' by mimicing usual python
        # behavior
        sys.path.insert(0, os.path.dirname(script))
        sys.argv = sys.argv[1:]
        globs = {'__file__': script}

        clear_contexts()
        runpy.run_path(script, globs, '__main__')

    except Exception:
        logger.exception('Unhandled exception', extra=extra)
        sys.exit(1)
    except SystemExit as e:
        code = e.code or 0
        if code != 0:
            logger.exception('SystemExit', extra=extra)
        sys.exit(code)
コード例 #20
0
ファイル: cli.py プロジェクト: TimothyFitz/skypipe
def run():
    parser = get_parser()
    args = parser.parse_args()

    dotcloud_endpoint = os.environ.get('DOTCLOUD_API_ENDPOINT', 
            'https://rest.dotcloud.com/v1')
    cli = DotCloudCLI(endpoint=dotcloud_endpoint)

    if args.setup:
        cloud.setup(cli)
    elif args.reset:
        cloud.destroy_satellite(cli)
        cli.success("Skypipe system reset. Now run `skypipe --setup`")
    elif args.satellite:
        os.environ['PORT_ZMQ'] = args.satellite
        runpy.run_path('/'.join([os.path.dirname(__file__), 'satellite', 'server.py']))
    else:
        skypipe_endpoint = os.environ.get("SATELLITE", load_satellite_endpoint())
        skypipe_endpoint = skypipe_endpoint or cloud.discover_satellite(cli, deploy=False)
        if not skypipe_endpoint:
            cli.die("Unable to locate satellite. Please run `skypipe --setup`")
        save_satellite_endpoint(skypipe_endpoint)

        if args.check:
            cli.success("Skypipe is ready for action")
        else:
            client.run(skypipe_endpoint, args.name)
コード例 #21
0
ファイル: flame_graph.py プロジェクト: nvdv/vprof
 def run_as_package(self):
     """Runs program as a Python package."""
     with _StatProfiler() as prof:
         try:
             runpy.run_path(self._run_object, run_name='__main__')
         except SystemExit:
             pass
     return prof
コード例 #22
0
ファイル: pundle.py プロジェクト: Deepwalker/pundler
def cmd_run():
    "executes given script"
    activate()
    import runpy
    sys.path.insert(0, '')
    script = sys.argv[2]
    sys.argv = [sys.argv[2]] + sys.argv[3:]
    runpy.run_path(script, run_name='__main__')
コード例 #23
0
ファイル: test_all.py プロジェクト: PlamenStilyianov/Python
def run( pkg_mod_iter ):
    """Run each module."""
    for package, module_iter in pkg_mod_iter:
        print( package )
        print( "="*len(package ) )
        print()
        for filename, module in module_iter:
            runpy.run_path( package+"/"+filename, run_name="__main__" )
コード例 #24
0
ファイル: __main__.py プロジェクト: HengWang/pytrace
def main():
    pop_self_from_argv()
    if len(sys.argv) == 0:
        reader_main()
    else:
        sys.path.append(os.getcwd())
        with trace_context():
            runpy.run_path(sys.argv[0], run_name='__main__')
コード例 #25
0
ファイル: profiler.py プロジェクト: nvdv/vprof
 def run_as_package(self, prof):
     """Runs program as a Python package."""
     prof.enable()
     try:
         runpy.run_path(self._run_object, run_name='__main__')
     except SystemExit:
         pass
     prof.disable()
コード例 #26
0
ファイル: __main__.py プロジェクト: traff/vmprof-python
def main():
    parser = build_argparser()
    args = parser.parse_args(sys.argv[1:])
    web = args.web

    if args.input:
        assert args.query is not None, "Using -i requires you to specify -q"
        forest = parse_jitlog(args.input)
        q = query.new_unsafe_query(args.query)
        objs = q(forest)
        pretty_printer.write(sys.stdout, objs)
        sys.exit(0)

    if args.upload:
        # parse_jitlog will append source code to the binary
        forest = parse_jitlog(args.program)
        if forest.exception_raised():
            print("ERROR:", forest.exception_raised())
            sys.exit(1)
        if forest.extract_source_code_lines():
            # only copy the tags if the jitlog has no source code yet!
            forest.copy_and_add_source_code_tags()
        jitlog_upload(forest.filepath, get_url(args.web_url, "api/jitlog//"))
        sys.exit(0)

    if not _jitlog:
        if '__pypy__' in sys.builtin_module_names:
            sys.stderr.write("No _jitlog module. This PyPy version is too old!\n")
        else:
            sys.stderr.write("No _jitlog module. Use PyPy instead of CPython!\n")

    if not web:
        prof_file = args.output
    else:
        prof_file = tempfile.NamedTemporaryFile(delete=False)
    prof_name = prof_file.name


    fd = os.open(prof_name, os.O_WRONLY | os.O_TRUNC | os.O_CREAT)
    _jitlog.enable(fd)

    try:
        sys.argv = [args.program] + args.args
        sys.path.insert(0, os.path.dirname(args.program))
        runpy.run_path(args.program, run_name='__main__')
    except BaseException as e:
        if not isinstance(e, (KeyboardInterrupt, SystemExit)):
            raise
    # not need to close fd, will be here
    _jitlog.disable()

    if web:
        forest = parse_jitlog(prof_name)
        if forest.extract_source_code_lines():
            # only copy the tags if the jitlog has no source code yet!
            forest.copy_and_add_source_code_tags()
        jitlog_upload(forest.filepath, get_url(args.web_url, "api/jitlog//"))
        forest.unlink_jitlog() # free space!
コード例 #27
0
ファイル: test_cli.py プロジェクト: bjoernricks/python-quilt
 def test_registration(self):
     with tmp_mapping(vars(sys)) as temp_sys:
         temp_sys.set("argv", ["pquilt", "push", "--help"])
         temp_sys.set("stdout", cStringIO())
         try:
             runpy.run_path("pquilt", run_name="__main__")
         except SystemExit as exit:
             self.assertEqual(exit.code, 0)
         self.assertGreater(sys.stdout.getvalue(), "")
コード例 #28
0
 def run_as_package_path(self, prof):
     """Runs program as package specified with file path."""
     import runpy
     prof.enable()
     try:
         runpy.run_path(self._run_object, run_name='__main__')
     except SystemExit:
         pass
     prof.disable()
コード例 #29
0
ファイル: mesonmain.py プロジェクト: mesonbuild/meson
 def run_runpython_command(self, options):
     import runpy
     if options.eval_arg:
         exec(options.script_file)
     else:
         sys.argv[1:] = options.script_args
         sys.path.insert(0, os.path.dirname(options.script_file))
         runpy.run_path(options.script_file, run_name='__main__')
     return 0
コード例 #30
0
ファイル: _eval.py プロジェクト: nicolasdespres/samurai
 def evaluate(self):
     with protect_sys_path(), \
          self._import_tracker, \
          self._open_tracker:
         sys.path = self.load_path() + sys.path
         samurai_sys.manifest = self.manifest
         samurai_sys.load_path = self.load_path()
         runpy.run_path(self.manifest,
                        run_name="__samurai_main__")
コード例 #31
0
def run_script():
    listb = app.children["listb"]
    s_path = listb.get(ACTIVE)
    p = multiprocessing.Process(name="print", target=lambda:run_path(s_path))
    p.start()
コード例 #32
0
import os
import runpy
from codecs import open

from setuptools import setup, find_packages

# Based on https://github.com/pypa/sampleproject/blob/master/setup.py
# and https://python-packaging-user-guide.readthedocs.org/

here = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

VERSION = runpy.run_path(os.path.join(here, "mitmproxy", "version.py"))["VERSION"]

setup(
    name="mitmproxy",
    version=VERSION,
    description="An interactive, SSL-capable, man-in-the-middle HTTP proxy for penetration testers and software developers.",
    long_description=long_description,
    url="http://mitmproxy.org",
    author="Aldo Cortesi",
    author_email="*****@*****.**",
    license="MIT",
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Development Status :: 5 - Production/Stable",
        "Environment :: Console",
        "Environment :: Console :: Curses",
        "Operating System :: MacOS :: MacOS X",
コード例 #33
0
ファイル: setup.py プロジェクト: k9ert/github-binary-upload
def get_version_from_pyfile(version_file="github_binary_upload.py"):
    file_globals = runpy.run_path(version_file)
    return file_globals["__version__"]
コード例 #34
0
# C4D Installer
# Copyright (C) 2016  Niklas Rosenstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os, sys, runpy
os.environ['UNINSTALLER'] = 'true'

if not getattr(sys, 'frozen', False):
    # Not in PyInstaller, run bootstrap.py now.
    runpy.run_path('bootstrapper.py', run_name='__main__')
コード例 #35
0
#!/usr/bin/env python3

from functools import partial
from runpy import run_path
from pathlib import Path

import numpy as np

from mpi4py import MPI
from distances_fort import dtw_cort

util = run_path(Path(__file__).absolute().parent.parent / "util.py")


def serie_pair_index_generator(number, rank, size):
    """ generator for pair index (i, j) such that i < j < number

    :param number: the upper bound
    :returns: pairs (lower, greater)
    :rtype: a generator
    """
    assert rank < size
    start = rank * number // (size * 2)
    end_inf = min((number + 1) // 2, (rank + 1) * ((number + 1) // 2) // size)
    end_sup = min(number // 2, (rank + 1) * number // (size * 2))

    for range_ in (
            range(start, end_inf),
            range(number - 1 - start, number - 1 - end_sup, -1),
    ):
        for _idx_greater in range_:
コード例 #36
0
def open_bonds():
   mf.destroy()
   runpy.run_path("bonds.py")
コード例 #37
0
def open_cash():
   mf.destroy()
   runpy.run_path("cash.py")
コード例 #38
0
ファイル: setup.py プロジェクト: CosmosAtlas/gruvbox_pygments
REQUIRED = ["pygments>=2.4", "IPython"]

here = os.path.abspath(os.path.dirname(__file__))
README = os.path.join(here, "README.rst")

try:
    with codecs.open(README, encoding="utf-8") as f:
        long_description = "\n" + f.read()
except FileNotFoundError:
    long_description = DESCRIPTION

about = {}

try:
    f = os.path.join(here, "gruvbox", "__version__.py")
    ret = runpy.run_path(f)
    about = ret["about"]
except OSError:  # the file doesn't exist so hard code it
    about = {"__version__": "0.0.2"}

setup(
    name=NAME,
    version=about["__version__"],
    description=DESCRIPTION,
    long_description=long_description,
    long_description_content_type="text/restructuredtext",
    author=AUTHOR,
    author_email=EMAIL,
    url="https://github.com/farisachugthai/gruvbox_pygments",
    packages=find_packages(
        exclude=["tests", "*.tests", "*.tests.*", "tests.*"]),
コード例 #39
0
        "follow the instructions at "
        "https://pip.pypa.io/en/stable/installing/#installing-with-get-pip-py")


def read(*filenames, **kwargs):
    encoding = kwargs.get("encoding", "utf-8")
    sep = kwargs.get("sep", "\n")
    buf = []
    for filename in filenames:
        with io.open(filename, encoding=encoding) as f:
            buf.append(f.read())
    return sep.join(buf)


root = os.path.dirname(os.path.realpath(__file__))
version = runpy.run_path(os.path.join(root, "nengo_dl",
                                      "version.py"))["version"]

import pkg_resources
import sys

# determine which tensorflow package to require
if "bdist_wheel" in sys.argv:
    # when building wheels we have to pick a requirement ahead of time (can't
    # check it at install time). so we'll go with tensorflow, since
    # that is the safest option
    tf_req = "tensorflow"
else:
    # check if one of the tensorflow packages is already installed (so that we
    # don't force tensorflow to be installed if e.g. tensorflow-gpu is already
    # there).
    # as of pep517 and pip>=10.0, pip will be running this file inside an isolated
コード例 #40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from runpy import run_path

from setuptools import find_packages, setup

# This appears to be the least annoying Python-version-agnostic way of loading
# an external file.
extras_require = run_path(
    os.path.join(os.path.dirname(__file__), "bionic",
                 "deps/extras.py"))["extras_require"]

with open("README.md") as readme_file:
    readme = readme_file.read()

requirements = [
    "attrs>=20.1",
    "cattrs",
    "PyYAML",
    "numpy",
    "pandas",
    "pyarrow",
    "pyrsistent",
]

setup(
    name="bionic",
    version="0.9.2",
    description=(
コード例 #41
0
ファイル: pyexe.py プロジェクト: smrtcdr/pyexe
def main():  # noqa
    import ctypes
    import os
    import six
    import sys
    import warnings

    AllModules = False

    if len(sys.argv) == 1 and not hasattr(sys, 'frozen'):
        AllModules = True
    if not AllModules and sys.argv[:2][-1] != '--all':
        pass
    else:
        # IMPORT ALL MODULES
        import modules_pyexe_list  # noqa, this is the output of modules_pyexe
        print(dir(modules_pyexe_list))  # for installers to include submodules
        # END IMPORT ALL MODULES
        # Import modules which failed to be included in the auto-generated list.
        import setuptools._vendor.pyparsing  # noqa

    def alternate_raw_input(prompt=None):
        """
        Write the prompt to stderr, then call raw_input without a prompt.  This
        is to try to mimic better what the python executable does.

        Enter: prompt: prompt to print to stderr.
        """
        if prompt and len(prompt):
            sys.stderr.write(prompt)
            sys.stderr.flush()
        return six.moves.input('')

    def get_env_flag(currentValue, key):
        """
        Check if the environment has a key.  Parse this as a positive integer,
        if possible, otherwise treat it like 1.  Return the greater of the
        current value and the parsed value.
        """
        if not os.environ.get(key):
            return currentValue
        try:
            value = int(os.environ.get(key))
            if value < 0:
                value = 1
        except ValueError:
            value = 1
        return max(currentValue, value)

    def print_version(details=1):
        """
        Print the current version.

        Enter: details: 0 if part of help, 1 for basic verison, 2 for more
                    details.
        """
        from py_version import Version, Description

        print('%s, Version %s' % (Description, Version))
        if details > 1:
            print('Python %s' % (sys.version))
            # pywin32
            import win32api
            fileinfo = win32api.GetFileVersionInfo(win32api.__file__, '\\')
            print('pywin32: %s' % str(fileinfo['FileVersionLS'] >> 16))
            # Others
            import importlib
            for module_name in ('pip', 'psutil', 'setuptools', 'six'):
                module = importlib.import_module(module_name)
                print('%s: %s' % (module_name, module.__version__))

    def run_file(runFile, runFileArgv, skipFirstLine, globenv):
        """
        Exec a file with a limited set of globals.  We can't use runpy.run_path
        for (a) skipped first line, (b) Python 2.7 and zipapps (pyz files).
        Rather than use run_path in the limited cases where it can be used, we
        use one code path for executing files in general.

        Enter: runFile: path of the file to exec.
               runFileArgv: arguments to set sys.argv to.
               SkipFileLine: True to skip the first line of the file.
               globenv: global environment to use.
        """
        import codecs
        import re
        import zipfile
        sys.argv[:] = runFileArgv
        if zipfile.is_zipfile(os.path.abspath(runFile)):
            sys.path[0:0] = [runFile]
            with zipfile.ZipFile(runFile) as zptr:
                src = zptr.open('__main__.py').read()
        else:
            if not Isolated:
                sys.path[0:0] = [os.path.split(os.path.abspath(runFile))[0]]
            with open(runFile, 'rb') as fptr:
                src = fptr.read()
                # This is similar to what universal newline support does
                useenc = 'utf-8' if sys.version_info >= (3, ) else 'latin-1'
                if src.startswith(codecs.BOM_UTF8):
                    useenc = 'utf-8'
                    src = src[len(codecs.BOM_UTF8):]
                src = src.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
                if skipFirstLine:
                    src = src.split(b'\n', 1)[1] if b'\n' in src else b''
                # first two lines may contain encoding:
                firsttwo = src.split(b'\n', 2)
                coding_re = re.compile(
                    r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
                try:
                    match = coding_re.match(firsttwo[0].decode('utf8'))
                except Exception:
                    match = None
                if match:
                    useenc = match.group(1)
                    src = b'\n'.join(firsttwo[1:])
                else:
                    try:
                        match = coding_re.match(firsttwo[1].decode('utf8'))
                    except Exception:
                        match = None
                    if match:
                        useenc = match.group(1)
                        src = b'\n'.join(firsttwo[:1] + firsttwo[2:])
                src = src.decode(useenc)
        # If we use anything other than the actual globals() dictionary,
        # multiprocessing doesn't work.  Therefore, mutate globals() and
        # merge back in when done.
        globs = globals()
        originalGlobals = globs.copy()
        globs.clear()
        globs.update(globenv)
        globs['__name__'] = '__main__'
        globs['__file__'] = runFile
        six.exec_(src, globs)
        # globs.clear()
        globs.update(originalGlobals)

    def skip_once(cls, method):
        """
        The first time a mthod of a class is called, skip doing the action.

        Enter: cls: the class instance with the method.
               method: the name of the method (a string).
        """
        orig = getattr(cls, method, None)

        def skip(*args, **kwargs):
            setattr(cls, method, orig)

        setattr(cls, method, skip)

    if hasattr(sys, 'frozen'):
        delattr(sys, 'frozen')
    Help = False
    Interactive = None
    InteractiveArgv = None
    Isolated = False
    NoSiteFlag = False
    Optimize = 0
    PrintVersion = 0
    QuietFlag = False
    RunCommand = None
    RunFile = None
    RunModule = None
    SkipFirstLine = False
    StartupFile = None
    TabcheckFlag = 0
    Unbuffered = False
    UseEnvironment = True
    VerboseFlag = 0
    Warning3k = 0
    WarningBytes = 0
    WarningDivision = None
    WarningOptions = []
    skip = 0
    sys.dont_write_bytecode = False
    for i in six.moves.range(1, len(sys.argv)):  # noqa
        if skip:
            skip -= 1
            continue
        arg = sys.argv[i]
        if arg.startswith('-') and len(arg) > 1 and arg[1:2] != '-':
            for let in arg[1:]:
                if let == 'b':
                    WarningBytes += 1
                elif let == 'B':
                    sys.dont_write_bytecode = True
                elif let == 'c':
                    RunCommand = sys.argv[i + 1 + skip]
                    RunCommandArgv = ['-c'] + sys.argv[i + 2 + skip:]
                    skip = len(sys.argv)
                elif let == 'd':
                    # We don't have to do anything for this flag, since we
                    # never bundle with a debug build of Python
                    pass
                elif let == 'E':
                    UseEnvironment = False
                elif let == 'h':
                    Help = True
                elif let == 'i':
                    Interactive = True
                elif let == 'I' and sys.version_info >= (3, ):
                    UseEnvironment = False
                    Isolated = True
                elif let == 'm' and i + 1 < len(sys.argv):
                    RunModule = sys.argv[i + 1 + skip]
                    RunModuleArgv = sys.argv[i + 1 + skip:]
                    skip = len(sys.argv)
                elif let == 'O':
                    Optimize += 1
                elif let == 'q' and sys.version_info >= (3, ):
                    QuietFlag = True
                elif let == 'Q' and sys.version_info < (3, ):
                    if arg.startswith('-' + let) and len(arg) > 2:
                        WarningDivision = arg[2:]
                    else:
                        WarningDivision = sys.argv[i + 1 + skip]
                        skip += 1
                    if WarningDivision not in ('old', 'warn', 'warnall',
                                               'new'):
                        sys.stderr.write(
                            """-Q option should be `-Qold', `-Qwarn', `-Qwarnall', or `-Qnew' only
usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `%s -h' for more information.
    """ % (sys.argv[0], sys.argv[0]))
                        sys.exit(2)
                    if arg.startswith('-' + let) and len(arg) > 2:
                        break
                elif let == 'R':
                    # We can't change the hash seed after start, so ignore it.
                    pass
                elif let == 's':
                    # We don't have to do anything for this flag, since we
                    # never have a local user site-packages directory in
                    # stand-alone mode
                    pass
                elif let == 'S':
                    NoSiteFlag = True
                elif let == 't' and sys.version_info < (3, ):
                    TabcheckFlag += 1
                elif let == 'u':
                    Unbuffered = True
                elif let == 'v':
                    VerboseFlag += 1
                elif let == 'V':
                    PrintVersion += 1
                elif let == 'W':
                    if arg.startswith('-' + let) and len(arg) > 2:
                        WarningOptions.append(arg[2:])
                        break
                    else:
                        WarningOptions.append(sys.argv[i + 1 + skip])
                        skip += 1
                elif let == 'x':
                    SkipFirstLine = True
                elif let == 'X':
                    # We don't have do anything for this flag, as the basic
                    # implementation doesn't have such options.
                    if arg.startswith('-' + let) and len(arg) > 2:
                        break
                    else:
                        skip += 1
                elif let == '3' and sys.version_info < (3, ):
                    Warning3k += 1
                    TabcheckFlag = max(TabcheckFlag, 1)
                else:
                    Help = True
        elif ((arg == '--check-hash-based-pycs'
               or arg.startswith('--check-hash-based-pycs='))
              and sys.version_info >= (3, 6)):
            # There is no exposure to this option in Python's DLL, so can't do
            # it
            if '=' not in arg:
                skip += 1
        elif arg == '--all':
            pass
        elif arg == '--help' or arg == '/?':
            Help = True
        elif arg == '--version':
            PrintVersion += 1
        elif arg == '-':
            Interactive = 'check'
            InteractiveArgv = ['-'] + sys.argv[i + 1 + skip:]
            skip = len(sys.argv)
        elif arg.startswith('-'):
            Help = True
        elif not RunFile:
            RunFile = sys.argv[i + skip]
            RunFileArgv = sys.argv[i + skip:]
            skip = len(sys.argv)
    if Help:
        print_version(0)
        print('usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...' %
              sys.argv[0])
        print(
            """Options and arguments (and corresponding environment variables):"""
        )
        if sys.version_info >= (3, ):
            print(
                """-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)""")
        print(
            """-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help, /?)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x""")
        if sys.version_info >= (3, ):
            print(
                """-I     : isolate Python from the user's environment (implies -E and -s)"""
            )
        print(
            """-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO    : remove doc-strings in addition to the -O optimizations""")
        if sys.version_info >= (3, ):
            print(
                """-q     : don't print version and copyright messages on interactive startup"""
            )
        if sys.version_info < (3, ):
            print(
                """-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew"""
            )
        print(
            """-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization""")
        if sys.version_info < (3, ):
            print(
                """-t     : issue warnings about inconsistent tab usage (-tt: issue errors)"""
            )
        print(
            """-u     : unbuffered binary stdout and stderr, stdin always buffered;
         also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version).  Use twice
         for more complete information.
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option""")
        if sys.version_info < (3, ):
            print(
                """-3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix"""
            )  # noqa
        print("""file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Stand-alone specific options:
--all  : imports all bundled modules.

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONCASEOK : ignore case in 'import' statements (Windows).""")
        sys.exit(0)
    if PrintVersion:
        print_version(PrintVersion)
        sys.exit(0)
    # Explicitly add the path of the current executable to the system paths and
    # its subpath of Lib\site-packages.  Installed Python always includes these
    # paths, but PyInstaller changes them to the expanded paths.
    sys.path[0:0] = [
        os.path.abspath(os.path.dirname(sys.executable)),
        os.path.abspath(
            os.path.join(os.path.dirname(sys.executable), 'Lib',
                         'site-packages'))
    ]
    if UseEnvironment:
        if os.environ.get('PYTHONDONTWRITEBYTECODE'):
            sys.dont_write_bytecode = True
        if Interactive is not True and os.environ.get('PYTHONINSPECT'):
            Interactive = 'check'
        Optimize = get_env_flag(Optimize, 'PYTHONOPTIMIZE')
        if os.environ.get('PYTHONPATH'):
            sys.path[0:0] = os.environ.get('PYTHONPATH').split(os.pathsep)
        StartupFile = os.environ.get('PYTHONSTARTUP')
        if Unbuffered is False and os.environ.get('PYTHONUNBUFFERED'):
            Unbuffered = True
        VerboseFlag = get_env_flag(VerboseFlag, 'PYTHONVERBOSE')
        if os.environ.get('PYTHONWARNINGS'):
            WarningOptions.extend(os.environ.get('PYTHONWARNINGS').split(','))
    if Isolated:
        # We have to suppress some environment effects
        os.environ.pop('PYTHONCASEOK', None)
        for key in list(sys.modules):  # for Python 3.x
            if hasattr(sys.modules[key], '_relax_case'):
                sys.modules[key]._relax_case = lambda: False
    if VerboseFlag:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_VerboseFlag').value = VerboseFlag
    if TabcheckFlag:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_TabcheckFlag').value = TabcheckFlag
    if Warning3k:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_Py3kWarningFlag').value = Warning3k
    if Optimize:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_OptimizeFlag').value = Optimize
    if WarningBytes:
        for idx, f in enumerate(warnings.filters):
            if f[2] == BytesWarning:
                warnings.filters[idx] = tuple(
                    ['default' if WarningBytes == 1 else 'error'] +
                    list(f)[1:])
        if not any([f for f in warnings.filters if f[2] == BytesWarning]):
            warnings.filterwarnings(
                'default' if WarningBytes == 1 else 'error',
                category=BytesWarning)
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_BytesWarningFlag').value = WarningBytes
    if WarningDivision == 'new':
        ctypes.c_int.in_dll(ctypes.pythonapi, '_Py_QnewFlag').value = 1
    elif WarningDivision in ('warn', 'warnall') or Warning3k:
        ctypes.c_int.in_dll(
            ctypes.pythonapi,
            'Py_DivisionWarningFlag').value = (2 if WarningDivision
                                               == 'warnall' else 1)
        warnings.filterwarnings('default',
                                category=DeprecationWarning,
                                message='classic [a-z]+ division')
    if Warning3k:
        warnings.filterwarnings('default', category=DeprecationWarning)
    sys.warnoptions[0:0] = WarningOptions
    warnings._processoptions(WarningOptions)
    bufsize = 1 if sys.version_info >= (3, ) else 0
    if Unbuffered:
        sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', bufsize)
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
        sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
    if not NoSiteFlag:
        import site
        site.main()
    # Generate the globals/locals environment
    globenv = {}
    for key in list(globals().keys()):
        if key.startswith('_') and key != '_frozen_name':
            globenv[key] = globals()[key]
    if RunFile:
        run_file(RunFile, RunFileArgv, SkipFirstLine, globenv)
    elif RunModule:
        import runpy
        sys.argv[:] = RunModuleArgv
        runpy.run_module(RunModule, run_name='__main__')
    elif RunCommand is not None:
        if not Isolated:
            sys.path[0:0] = ['']
        sys.argv[:] = RunCommandArgv
        six.exec_(RunCommand, globenv)
    elif Interactive is None:
        Interactive = 'check'
    if Interactive:
        if not Isolated:
            sys.path[0:0] = ['']
        if InteractiveArgv:
            sys.argv[:] = InteractiveArgv
        if Interactive is True or sys.stdin.isatty():
            if not RunFile and not RunModule and not RunCommand and StartupFile:
                import runpy
                runpy.run_path(StartupFile, run_name='__main__')
            import code
            cons = code.InteractiveConsole(locals=globenv)
            if not sys.stdout.isatty():
                cons.raw_input = alternate_raw_input
                if not Unbuffered:
                    sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
                    sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
            banner = 'Python %s' % sys.version
            if not NoSiteFlag:
                banner += '\nType "help", "copyright", "credits" or "license" for more information.'
            if RunModule or RunCommand or QuietFlag:
                banner = ''
                if sys.version_info < (3, ):
                    skip_once(cons, 'write')
            kwargs = {}
            if sys.version_info >= (3, 6):
                kwargs['exitmsg'] = ''
            cons.interact(banner=banner, **kwargs)
        else:
            src = sys.stdin.read()
            # This doesn't work the way I expect for some reason
            #  interp = code.InteractiveInterpreter(locals=globenv)
            #  interp.runsource(src, '<stdin>')
            # But an exec works fine
            globenv['__file__'] = '<stdin>'
            six.exec_(src, globenv)
コード例 #42
0
ファイル: main.py プロジェクト: Pikernot/BubbleShooter
 def update(self):
     runpy.run_path('game.py', run_name='__main__')
コード例 #43
0
def main() -> None:
    python_version = ".".join(str(v) for v in sys.version_info[:3])
    libkdumpfile = f'with{"" if drgn._with_libkdumpfile else "out"} libkdumpfile'
    version = f"drgn {drgn.__version__} (using Python {python_version}, elfutils {drgn._elfutils_version}, {libkdumpfile})"
    parser = argparse.ArgumentParser(prog="drgn",
                                     description="Scriptable debugger")

    program_group = parser.add_argument_group(
        title="program selection", ).add_mutually_exclusive_group()
    program_group.add_argument("-k",
                               "--kernel",
                               action="store_true",
                               help="debug the running kernel (default)")
    program_group.add_argument("-c",
                               "--core",
                               metavar="PATH",
                               type=str,
                               help="debug the given core dump")
    program_group.add_argument(
        "-p",
        "--pid",
        metavar="PID",
        type=int,
        help="debug the running process with the given PID",
    )

    symbol_group = parser.add_argument_group("debugging symbols")
    symbol_group.add_argument(
        "-s",
        "--symbols",
        metavar="PATH",
        type=str,
        action="append",
        help=
        "load additional debugging symbols from the given file; this option may be given more than once",
    )
    default_symbols_group = symbol_group.add_mutually_exclusive_group()
    default_symbols_group.add_argument(
        "--main-symbols",
        dest="default_symbols",
        action="store_const",
        const={"main": True},
        help=
        "only load debugging symbols for the main executable and those added with -s; "
        "for userspace programs, this is currently equivalent to --no-default-symbols",
    )
    default_symbols_group.add_argument(
        "--no-default-symbols",
        dest="default_symbols",
        action="store_const",
        const={},
        help=
        "don't load any debugging symbols that were not explicitly added with -s",
    )

    parser.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        help=
        "don't print non-fatal warnings (e.g., about missing debugging information)",
    )
    parser.add_argument(
        "script",
        metavar="ARG",
        type=str,
        nargs=argparse.REMAINDER,
        help="script to execute instead of running in interactive mode",
    )
    parser.add_argument("--version", action="version", version=version)

    args = parser.parse_args()

    prog = drgn.Program()
    if args.core is not None:
        prog.set_core_dump(args.core)
    elif args.pid is not None:
        prog.set_pid(args.pid or os.getpid())
    else:
        prog.set_kernel()
    if args.default_symbols is None:
        args.default_symbols = {"default": True, "main": True}
    try:
        prog.load_debug_info(args.symbols, **args.default_symbols)
    except drgn.MissingDebugInfoError as e:
        if not args.quiet:
            print(str(e), file=sys.stderr)

    init_globals: Dict[str, Any] = {"prog": prog}
    if args.script:
        sys.argv = args.script
        runpy.run_path(args.script[0],
                       init_globals=init_globals,
                       run_name="__main__")
    else:
        import atexit
        import readline

        from drgn.internal.rlcompleter import Completer

        init_globals["drgn"] = drgn
        drgn_globals = [
            "NULL",
            "Object",
            "cast",
            "container_of",
            "execscript",
            "offsetof",
            "reinterpret",
            "sizeof",
        ]
        for attr in drgn_globals:
            init_globals[attr] = getattr(drgn, attr)
        init_globals["__name__"] = "__main__"
        init_globals["__doc__"] = None

        histfile = os.path.expanduser("~/.drgn_history")
        try:
            readline.read_history_file(histfile)
        except OSError as e:
            if not isinstance(e, FileNotFoundError) and not args.quiet:
                print("could not read history:", str(e), file=sys.stderr)

        def write_history_file() -> None:
            try:
                readline.write_history_file(histfile)
            except OSError as e:
                if not args.quiet:
                    print("could not write history:", str(e), file=sys.stderr)

        atexit.register(write_history_file)

        readline.set_history_length(1000)
        readline.parse_and_bind("tab: complete")
        readline.set_completer(Completer(init_globals).complete)
        atexit.register(lambda: readline.set_completer(None))

        sys.displayhook = displayhook

        banner = (version + """
For help, type help(drgn).
>>> import drgn
>>> from drgn import """ + ", ".join(drgn_globals))
        if prog.flags & drgn.ProgramFlags.IS_LINUX_KERNEL:
            banner += "\n>>> from drgn.helpers.linux import *"
            module = importlib.import_module("drgn.helpers.linux")
            for name in module.__dict__["__all__"]:
                init_globals[name] = getattr(module, name)
        code.interact(banner=banner, exitmsg="", local=init_globals)
コード例 #44
0
def open_home():
  mf.destroy()
  runpy.run_path("home.py")
コード例 #45
0
import collections
import time
import datetime
import hashlib
import random
import binascii
import sys
import re
import runpy
import signal

if len(sys.argv) < 2:
    config = runpy.run_module("config")
elif len(sys.argv) == 2:
    # launch with own config
    config = runpy.run_path(sys.argv[1])
else:
    # undocumented way of launching
    config = {}
    config["PORT"] = int(sys.argv[1])
    secrets = sys.argv[2].split(",")
    config["USERS"] = {
        "user%d" % i: secrets[i].zfill(32)
        for i in range(len(secrets))
    }
    if len(sys.argv) > 3:
        config["AD_TAG"] = sys.argv[3]

PORT = config["PORT"]
USERS = config["USERS"]
AD_TAG = bytes.fromhex(config.get("AD_TAG", ""))
コード例 #46
0
ファイル: test_aided.py プロジェクト: Agchai52/MPRNet
#                 + glob(os.path.join(inp_dir, '*.PNG')))

# For nonBlind only
# f_test = open("./dataset/AidedDeblur/test_instance_names.txt", "r")
# For nonBlind real images only
f_test = open("./dataset/real_images/real_image_names.txt", "r")
imgsName = f_test.readlines()
imgsName = [line.rstrip() for line in imgsName]
f_test.close()
files = sorted(imgsName)

if len(files) == 0:
    raise Exception("No files found at {inp_dir}")

# Load corresponding model architecture and weights
load_file = run_path(os.path.join(task, "MPRNet.py"))
model = load_file['MPRNet']()
model.cuda()

weights = os.path.join(task, "pretrained_models", "model_"+task.lower()+".pth")
load_checkpoint(model, weights)
model.eval()

img_multiple_of = 8
start_time = time.time()

for file_ in files:
    # For NonBLind Only
    # file_ = file_ + '_blur_err.png'
    # For real images only
    file_ = "./dataset" + file_[1:] + '.png'
コード例 #47
0
 def create_ns(init_globals):
     return run_path(script_name, init_globals, run_name)
コード例 #48
0
def create_png_files(raise_exceptions=False):
    from ase.utils import workdir
    try:
        check_call(['povray', '-h'], stderr=DEVNULL)
    except (FileNotFoundError, CalledProcessError):
        warnings.warn('No POVRAY!')
        # Replace write_pov with write_png:
        from ase.io import pov
        from ase.io.png import write_png

        def write_pov(filename,
                      atoms,
                      povray_settings={},
                      isosurface_data=None,
                      **generic_projection_settings):

            write_png(
                Path(filename).with_suffix('.png'), atoms,
                **generic_projection_settings)

            class DummyRenderer:
                def render(self):
                    pass

            return DummyRenderer()

        pov.write_pov = write_pov

    for dir, pyname, outnames in creates():
        path = join(dir, pyname)
        t0 = os.stat(path)[ST_MTIME]
        run = False
        for outname in outnames:
            try:
                t = os.stat(join(dir, outname))[ST_MTIME]
            except OSError:
                run = True
                break
            else:
                if t < t0:
                    run = True
                    break
        if run:
            print('running:', path)
            with workdir(dir):
                import matplotlib.pyplot as plt
                plt.figure()
                try:
                    runpy.run_path(pyname)
                except KeyboardInterrupt:
                    return
                except Exception:
                    if raise_exceptions:
                        raise
                    else:
                        traceback.print_exc()

            for n in plt.get_fignums():
                plt.close(n)

            for outname in outnames:
                print(dir, outname)
コード例 #49
0
#!/usr/bin/env python
import subprocess
import sys
import setuptools
import runpy

# Ref : https://packaging.python.org/single_source_version/#single-sourcing-the-version
# runpy is safer and a better habit than exec
version = runpy.run_path('palimport/_version.py')
__version__ = version.get('__version__')


# Best Flow :
# Clean previous build & dist
# $ gitchangelog >CHANGELOG.rst
# change version in code and changelog
# $ python setup.py prepare_release
# WAIT FOR TRAVIS CHECKS
# $ python setup.py publish
# => TODO : try to do a simpler "release" command


# Clean way to add a custom "python setup.py <command>"
# Ref setup.py command extension : https://blog.niteoweb.com/setuptools-run-custom-code-in-setup-py/
class PrepareReleaseCommand(setuptools.Command):
    """Command to release this package to Pypi"""
    description = "prepare a release of palimport"
    user_options = []

    def initialize_options(self):
        """init options"""
コード例 #50
0
ファイル: run_python.py プロジェクト: rossning92/MyScripts
    "win32con": "pywin32",
    "win32gui": "pywin32",
    "win32ui": "pywin32",
    "yaml": "pyyaml",
}


class MyMetaPathFinder(MetaPathFinder):
    """
    A importlib.abc.MetaPathFinder to auto-install missing modules using pip
    """
    def find_spec(fullname, path, target=None):
        if path == None:
            if fullname in PYTHON_MODULE_LIST:
                installed = subprocess.call([
                    sys.executable,
                    "-m",
                    "pip",
                    "install",
                    PYTHON_MODULE_LIST[fullname],
                ])
                if installed == 0:
                    return import_module(fullname)


sys.meta_path.append(MyMetaPathFinder)

if __name__ == "__main__":
    del sys.argv[0]
    runpy.run_path(sys.argv[0], run_name="__main__")
コード例 #51
0
def toString(value):
    h = value.count('!')
    t = value.count(',')
    u = value.count('.')
    dcml = h * 100 + t * 10 + u * 1
    return chr(dcml)


# creates output.py with converted code file
def generateOutput(tokens):
    print("Generating output.py file...")
    f = open("output.py", "w", newline="")
    for token in tokens:
        f.write(token)
    f.close()


# main execution of the parser
code = readProgramFile("helloworld.rao")
tokens = tokenize(code)
checkHeader(tokens)
checkFooter(tokens)
syntaxChecker(tokens)
stringList(tokens)
parser(tokens)
Kevin.fileCheck(tokens)
generateOutput(tokens)
print("Testing your patience...")
print("Executing output.py...\n")
runpy.run_path('output.py')  # desperate times, desperate measures
コード例 #52
0
# -*- encoding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import runpy
from distutils.extension import Extension

# Get the version number.
__version_str__ = runpy.run_path("maxflow/version.py")["__version_str__"]


# Lazy evaluate extension definition, to allow correct requirements install
class lazy_cythonize(list):
    def __init__(self, callback):
        self._list, self.callback = None, callback

    def c_list(self):
        if self._list is None: self._list = self.callback()
        return self._list

    def __iter__(self):
        for e in self.c_list():
            yield e

    def __getitem__(self, ii):
        return self.c_list()[ii]

    def __len__(self):
コード例 #53
0
]
content_package.insert(0, "azure-common")

# Package final:
if "install" in sys.argv:
    packages = content_package
elif "travis_deploy" in sys.argv:
    from build_package import travis_build_package
    sys.exit(travis_build_package())
else:
    packages = nspkg_packages + content_package + meta_package

for pkg_name in packages:
    pkg_setup_folder = os.path.join(root_folder, pkg_name)
    pkg_setup_path = os.path.join(pkg_setup_folder, 'setup.py')

    try:
        saved_dir = os.getcwd()
        saved_syspath = sys.path

        os.chdir(pkg_setup_folder)
        sys.path = [pkg_setup_folder] + copy.copy(saved_syspath)

        print("Start ", pkg_setup_path)
        result = runpy.run_path(pkg_setup_path)
    except Exception as e:
        print(e, file=sys.stderr)
    finally:
        os.chdir(saved_dir)
        sys.path = saved_syspath
コード例 #54
0
def run_script(args):
    sys.argv = [args.path] + args.args
    runpy.run_path(args.path, run_name='__main__')
コード例 #55
0
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
import os.path
import runpy

import setuptools
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
    long_description = f.read()

version_mod = runpy.run_path("aioxmpp/version.py")

install_requires = [
    'aiosasl>=0.3',  # need 0.2+ for LGPLv3
    'aioopenssl>=0.1',
    'babel~=2.3',
    'dnspython~=1.0',
    'lxml~=3.6',
    'multidict~=2.0',
    'orderedset>=1.2',
    'pyOpenSSL',
    'pyasn1',
    'pyasn1_modules',
    'tzlocal~=1.2'
]
コード例 #56
0
ファイル: setup.py プロジェクト: lkollar/auditwheel-patchelf
def get_version():
    prepare_version()
    return runpy.run_path(VERSION_FILE)['__version__']
コード例 #57
0
def open_gold():
   mf.destroy()
   runpy.run_path("gold.py")
コード例 #58
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""

from setuptools import setup, find_packages
import runpy
__version__ = runpy.run_path('inferno/version.py')['__version__']

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    # TODO: put package requirements here
    "pip>=8.1.2",
    "torch>=0.1.12",
    "dill",
    "pyyaml",
    "scipy>=0.13.0",
    "h5py",
    "numpy>=1.8",
    "scikit-image",
    "torchvision",
    "tqdm"
]

setup_requirements = ['pytest-runner']

test_requirements = ['pytest', 'unittest']
コード例 #59
0
def open_stocks():
   mf.destroy()
   runpy.run_path("mf.py")
コード例 #60
0
def open_re():
   mf.destroy()
   runpy.run_path("re.py")