當前位置: 首頁>>代碼示例>>Python>>正文


Python runpy.run_path方法代碼示例

本文整理匯總了Python中runpy.run_path方法的典型用法代碼示例。如果您正苦於以下問題:Python runpy.run_path方法的具體用法?Python runpy.run_path怎麽用?Python runpy.run_path使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在runpy的用法示例。


在下文中一共展示了runpy.run_path方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _profile_package

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def _profile_package(self):
        """Runs cProfile on a package."""
        prof = cProfile.Profile()
        prof.enable()
        try:
            runpy.run_path(self._run_object, run_name='__main__')
        except SystemExit:
            pass
        prof.disable()
        prof_stats = pstats.Stats(prof)
        prof_stats.calc_callees()
        return {
            'objectName': self._object_name,
            'callStats': self._transform_stats(prof_stats),
            'totalTime': prof_stats.total_tt,
            'primitiveCalls': prof_stats.prim_calls,
            'totalCalls': prof_stats.total_calls,
            'timestamp': int(time.time())
        } 
開發者ID:nvdv,項目名稱:vprof,代碼行數:21,代碼來源:profiler.py

示例2: _profile_package

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def _profile_package(self):
        """Runs statistical profiler on a package."""
        with _StatProfiler() as prof:
            prof.base_frame = inspect.currentframe()
            try:
                runpy.run_path(self._run_object, run_name='__main__')
            except SystemExit:
                pass

        call_tree = prof.call_tree
        return {
            'objectName': self._object_name,
            'sampleInterval': _SAMPLE_INTERVAL,
            'runTime': prof.run_time,
            'callStats': call_tree,
            'totalSamples': call_tree.get('sampleCount', 0),
            'timestamp': int(time.time())
        } 
開發者ID:nvdv,項目名稱:vprof,代碼行數:20,代碼來源:flame_graph.py

示例3: _profile_package

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def _profile_package(self):
        """Calculates heatmap for a package."""
        with _CodeHeatmapCalculator() as prof:
            try:
                runpy.run_path(self._run_object, run_name='__main__')
            except SystemExit:
                pass

        heatmaps = []
        for filename, heatmap in prof.heatmap.items():
            if os.path.isfile(filename):
                heatmaps.append(
                    self._format_heatmap(
                        filename, heatmap, prof.execution_count[filename]))

        run_time = sum(heatmap['runTime'] for heatmap in heatmaps)
        return {
            'objectName': self._run_object,
            'runTime': run_time,
            'heatmaps': heatmaps
        } 
開發者ID:nvdv,項目名稱:vprof,代碼行數:23,代碼來源:code_heatmap.py

示例4: run_script

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def run_script(self, input="", args=("-",), substfile="xx yy\n"):
        substfilename = test_support.TESTFN + ".subst"
        with open(substfilename, "w") as file:
            file.write(substfile)
        self.addCleanup(test_support.unlink, substfilename)

        argv = ["fixcid.py", "-s", substfilename] + list(args)
        script = os.path.join(scriptsdir, "fixcid.py")
        with test_support.swap_attr(sys, "argv", argv), \
                test_support.swap_attr(sys, "stdin", StringIO(input)), \
                test_support.captured_stdout() as output:
            try:
                runpy.run_path(script, run_name="__main__")
            except SystemExit as exit:
                self.assertEqual(exit.code, 0)
        return output.getvalue() 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_tools.py

示例5: get_info_from_setup

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def get_info_from_setup(path):
    """Mock setuptools.setup(**kargs) to get
    package information about requirements and extras
    """
    preserve = {}

    def _save_info(**setup_args):
        preserve['args'] = setup_args

    import setuptools
    original_setup = setuptools.setup
    setuptools.setup = _save_info
    import runpy
    runpy.run_path(os.path.join(path, 'setup.py'), run_name='__main__')
    setuptools.setup = original_setup
    return preserve.get('args') 
開發者ID:Deepwalker,項目名稱:pundler,代碼行數:18,代碼來源:pundle.py

示例6: main

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def main(env, interactive, shell_interface, script, script_args):
    global_vars = {"env": env}
    if script:
        sys.argv[1:] = script_args
        global_vars = runpy.run_path(
            script, init_globals=global_vars, run_name="__main__"
        )
    if not script or interactive:
        if console._isatty(sys.stdin):
            if not env:
                _logger.info("No environment set, use `-d dbname` to get one.")
            console.Shell.interact(global_vars, shell_interface)
            if env:
                env.cr.rollback()
        else:
            sys.argv[:] = [""]
            global_vars["__name__"] = "__main__"
            exec(sys.stdin.read(), global_vars) 
開發者ID:acsone,項目名稱:click-odoo,代碼行數:20,代碼來源:cli.py

示例7: get_migrations

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def get_migrations():
    file_names = sorted(os.listdir(MIGRATIONS_ROOT))
    matcher = re.compile(r'^(\d\d\d\d)_(\w+)\.py')
    migrations = []
    for file_name in file_names:
        match = matcher.match(file_name)
        if match:
            number_string, slug = match.groups()
            number = int(number_string)
            if number == 0:
                continue
            get_new_resource_address = runpy.run_path(os.path.join(MIGRATIONS_ROOT, file_name)).get('get_new_resource_address')
            migrations.append(
                Migration(number=number, slug=slug,
                          get_new_resource_address=get_new_resource_address))
    return migrations 
開發者ID:dimagi,項目名稱:commcare-cloud,代碼行數:18,代碼來源:terraform_migrate_state.py

示例8: exec_file

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def exec_file(file, global_variables):
    '''Executes the provided script as if it were the original script provided
    to python.exe. The functionality is similar to `runpy.run_path`, which was
    added in Python 2.7/3.2.

    The following values in `global_variables` will be set to the following
    values, if they are not already set::
        __name__ = '<run_path>'
        __file__ = file
        __package__ = __name__.rpartition('.')[0] # 2.6 and later
        __cached__ = None # 3.2 and later
        __loader__ = sys.modules['__main__'].__loader__ # 3.3 and later

    The `sys.modules` entry for ``__name__`` will be set to a new module, and
    ``sys.path[0]`` will be changed to the value of `file` without the filename.
    Both values are restored when this function exits.
    '''
    f = open(file, "rb")
    try:
        code = f.read().replace(to_bytes('\r\n'), to_bytes('\n')) + to_bytes('\n')
    finally:
        f.close()
    exec_code(code, file, global_variables) 
開發者ID:ms-iot,項目名稱:iot-utilities,代碼行數:25,代碼來源:visualstudio_py_util.py

示例9: shell

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def shell(runtime, script=None, python=None):
    # alias for backwards-compatibility
    variables = {
        "config": runtime,
        "runtime": runtime,
        "project_config": runtime.project_config,
    }

    if script:
        if python:
            raise click.UsageError("Cannot specify both --script and --python")
        runpy.run_path(script, init_globals=variables)
    elif python:
        exec(python, variables)
    else:
        code.interact(local=variables) 
開發者ID:SFDO-Tooling,項目名稱:CumulusCI,代碼行數:18,代碼來源:cci.py

示例10: run_kitten

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def run_kitten(kitten: str, run_name: str = '__main__') -> None:
    import runpy
    original_kitten_name = kitten
    kitten = resolved_kitten(kitten)
    set_debug(kitten)
    try:
        runpy.run_module('kittens.{}.main'.format(kitten), run_name=run_name)
        return
    except ImportError:
        pass
    # Look for a custom kitten
    if not kitten.endswith('.py'):
        kitten += '.py'
    from kitty.constants import config_dir
    path = path_to_custom_kitten(config_dir, kitten)
    if not os.path.exists(path):
        print('Available builtin kittens:', file=sys.stderr)
        for kitten in all_kitten_names():
            print(kitten, file=sys.stderr)
        raise SystemExit('No kitten named {}'.format(original_kitten_name))
    m = runpy.run_path(path, init_globals={'sys': sys, 'os': os}, run_name='__run_kitten__')
    m['main'](sys.argv) 
開發者ID:kovidgoyal,項目名稱:kitty,代碼行數:24,代碼來源:runner.py

示例11: _import_all_stats

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def _import_all_stats():
    """
    Import all stats (prepackaged ones and user defined ones).
    This must only ever be called once. Otherwise they are imported
    multiple times.
    """
    here = os.path.dirname(os.path.realpath(__file__))
    default_stat_dir = os.path.join(here, 'stats', '*.py')
    custom_stat_dir = os.path.join(config.config_dir, 'stats', '*.permon.py')

    default_stat_files = glob.glob(default_stat_dir)
    custom_stat_files = glob.glob(custom_stat_dir)

    dup = set(os.path.basename(x) for x in default_stat_files).intersection(
          set(os.path.basename(x) for x in custom_stat_files))
    assert len(dup) == 0, \
        ('Custom stat files must not have the same name as default ones. '
         f'{dup} collides.')

    for path in default_stat_files + custom_stat_files:
        runpy.run_path(path, run_name=path) 
開發者ID:bminixhofer,項目名稱:permon,代碼行數:23,代碼來源:__init__.py

示例12: from_counted_unknown_properties

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def from_counted_unknown_properties(filename):
    histograms = collections.OrderedDict()
    properties = runpy.run_path(filename)["COUNTED_UNKNOWN_PROPERTIES"]

    # NOTE(emilio): Unlike ServoCSSProperties, `prop` here is just the property
    # name.
    #
    # We use the same naming as CSS properties so that we don't get
    # discontinuity when we implement or prototype them.
    for prop in properties:
        add_css_property_counters(histograms, prop)
    return histograms 
開發者ID:mozilla,項目名稱:probe-scraper,代碼行數:14,代碼來源:histogram_tools.py

示例13: profile_package

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def profile_package(self):
        """Returns memory stats for a package."""
        target_modules = base_profiler.get_pkg_module_names(self._run_object)
        try:
            with _CodeEventsTracker(target_modules) as prof:
                prof.compute_mem_overhead()
                runpy.run_path(self._run_object, run_name='__main__')
        except SystemExit:
            pass
        return prof, None 
開發者ID:nvdv,項目名稱:vprof,代碼行數:12,代碼來源:memory_profiler.py

示例14: _check_script

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def _check_script(self, script_name, expected_name, expected_file,
                            expected_argv0, expected_package):
        result = run_path(script_name)
        self.assertEqual(result["__name__"], expected_name)
        self.assertEqual(result["__file__"], expected_file)
        self.assertIn("argv0", result)
        self.assertEqual(result["argv0"], expected_argv0)
        self.assertEqual(result["__package__"], expected_package) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:10,代碼來源:test_runpy.py

示例15: _check_import_error

# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_path [as 別名]
def _check_import_error(self, script_name, msg):
        msg = re.escape(msg)
        self.assertRaisesRegexp(ImportError, msg, run_path, script_name) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:5,代碼來源:test_runpy.py


注:本文中的runpy.run_path方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。