当前位置: 首页>>代码示例>>Python>>正文


Python IPython.get_ipython方法代码示例

本文整理汇总了Python中IPython.get_ipython方法的典型用法代码示例。如果您正苦于以下问题:Python IPython.get_ipython方法的具体用法?Python IPython.get_ipython怎么用?Python IPython.get_ipython使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IPython的用法示例。


在下文中一共展示了IPython.get_ipython方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _process_line_arguments

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def _process_line_arguments(line_arguments):
    from IPython import get_ipython
    args = []
    kwargs = {}
    reached_kwargs = False
    for arg in line_arguments.split():
        if '=' in arg:
            reached_kwargs = True
            key, value = arg.split('=')
            value = eval(value, get_ipython().user_ns)
            if key in kwargs:
                raise ValueError('Duplicate keyword argument `{}`.'.format(key))
            kwargs[key] = value
        else:
            if reached_kwargs:
                raise ValueError('Positional argument `{}` after keyword argument.'.format(arg))
            args.append(arg)
    return args, kwargs 
开发者ID:airbnb,项目名称:omniduct,代码行数:20,代码来源:magics.py

示例2: __init__

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def __init__(self, credentials, project_id, region):
        """
        args:
            credentials: Path to the credentials json file
            project_id: project_id of your project in GCP
            region: region of your GCP project
        """
        self.credentials = credentials
        self.project_id = project_id
        self.region = region
        self.provider = "google"
        self.config = terrascript.Terrascript()
        self.config += terrascript.provider.google(
            credentials=self.credentials, project=self.project_id, region=self.region
        )
        with open("main.tf.json", "w") as main_config:
            json.dump(self.config, main_config, indent=2, sort_keys=False)

        if IPython.get_ipython():
            terraform_notebook.init()
        else:
            terraform_script.init() 
开发者ID:OpenMined,项目名称:PySyft,代码行数:24,代码来源:gcloud.py

示例3: compute_instance

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def compute_instance(self, name, machine_type, zone, image_family, apply=True):
        """
        args:
            name: name of the compute instance
            machine_type: the type of machine
            zone: zone of your GCP project
            image_family: image of the OS
            apply: to call terraform apply at the end
        """
        self.config += terrascript.resource.google_compute_instance(
            name,
            name=name,
            machine_type=machine_type,
            zone=zone,
            boot_disk={"initialize_params": {"image": image_family}},
            network_interface={"network": "default", "access_config": {}},
        )
        with open("main.tf.json", "w") as main_config:
            json.dump(self.config, main_config, indent=2, sort_keys=False)

        if apply:
            if IPython.get_ipython():
                terraform_notebook.apply()
            else:
                terraform_script.apply() 
开发者ID:OpenMined,项目名称:PySyft,代码行数:27,代码来源:gcloud.py

示例4: quick_completer

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def quick_completer(cmd, completions):
    """ Easily create a trivial completer for a command.

    Takes either a list of completions, or all completions in string (that will
    be split on whitespace).

    Example::

        [d:\ipython]|1> import ipy_completers
        [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
        [d:\ipython]|3> foo b<TAB>
        bar baz
        [d:\ipython]|3> foo ba
    """

    if isinstance(completions, basestring):
        completions = completions.split()

    def do_complete(self, event):
        return completions

    get_ipython().set_hook('complete_command',do_complete, str_key = cmd) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:24,代码来源:completerlib.py

示例5: _get_qt_app

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def _get_qt_app():
    app = None

    if in_ipython():
        from IPython import get_ipython
        ipython = get_ipython()
        ipython.magic('gui qt')

        from IPython.external.qt_for_kernel import QtGui
        app = QtGui.QApplication.instance()

    if app is None:
        from PyQt5.QtWidgets import QApplication
        app = QApplication.instance()
        if not app:
            app = QApplication([''])

    return app 
开发者ID:MICA-MNI,项目名称:BrainSpace,代码行数:20,代码来源:base.py

示例6: test_create_cell_debug

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def test_create_cell_debug(self, mock_default_context, mock_notebook_environment):
    env = {}
    mock_default_context.return_value = TestCases._create_context()
    mock_notebook_environment.return_value = env
    IPython.get_ipython().user_ns = env

    # cell output is empty when debug is True
    output = google.datalab.contrib.pipeline.commands._pipeline._create_cell(
        {'name': 'foo_pipeline', 'debug': True}, self.sample_cell_body)
    self.assertTrue(len(output) > 0)

    output = google.datalab.contrib.pipeline.commands._pipeline._create_cell(
        {'name': 'foo_pipeline', 'debug': False}, self.sample_cell_body)
    self.assertTrue(output is None)

    output = google.datalab.contrib.pipeline.commands._pipeline._create_cell(
        {'name': 'foo_pipeline'}, self.sample_cell_body)
    self.assertTrue(output is None) 
开发者ID:googledatalab,项目名称:pydatalab,代码行数:20,代码来源:pipeline_tests.py

示例7: _view

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def _view(args, cell):
  csv = datalab.data.Csv(args['input'])
  num_lines = int(args['count'] or 5)
  headers = None
  if cell:
    ipy = IPython.get_ipython()
    config = _utils.parse_config(cell, ipy.user_ns)
    if 'columns' in config:
      headers = [e.strip() for e in config['columns'].split(',')]
  df = pd.DataFrame(csv.browse(num_lines, headers))
  if args['profile']:
    # TODO(gram): We need to generate a schema and type-convert the columns before this
    # will be useful for CSV
    return _utils.profile_df(df)
  else:
    return IPython.core.display.HTML(df.to_html(index=False)) 
开发者ID:googledatalab,项目名称:pydatalab,代码行数:18,代码来源:_csv.py

示例8: register_json_formatter

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def register_json_formatter(cls: Type, to_dict_method_name: str = 'to_dict'):
    """
    TODO
    :param cls:
    :param to_dict_method_name:
    :return:
    """
    if not hasattr(cls, to_dict_method_name) or not callable(getattr(cls, to_dict_method_name)):
        raise ValueError(f'{cls} must define a {to_dict_method_name}() method')

    try:
        import IPython
        import IPython.display

        if IPython.get_ipython() is not None:
            def obj_to_dict(obj):
                return getattr(obj, to_dict_method_name)()

            ipy_formatter = IPython.get_ipython().display_formatter.formatters['application/json']
            ipy_formatter.for_type(cls, obj_to_dict)

    except ImportError:
        pass 
开发者ID:dcs4cop,项目名称:xcube,代码行数:25,代码来源:ipython.py

示例9: _patch_ipython_excepthook

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def _patch_ipython_excepthook(**kwargs):
    """ Replace ipython's built-in traceback printer, excellent though it is"""
    global ipy_tb

    blacklist = kwargs.get('suppressed_paths', [])
    blacklist.append('site-packages/IPython/')
    kwargs['suppressed_paths'] = blacklist

    if 'file' in kwargs:
        del kwargs['file']

    def format_tb(*exc_tuple, **__):
        unstructured_tb = format(exc_tuple, **kwargs)
        structured_tb = [unstructured_tb]  # \*coughs*
        return structured_tb

    import IPython
    shell = IPython.get_ipython()
    if ipy_tb is None:
        ipy_tb = shell.InteractiveTB.structured_traceback
    shell.InteractiveTB.structured_traceback = format_tb 
开发者ID:cknd,项目名称:stackprinter,代码行数:23,代码来源:__init__.py

示例10: start_watching_memory

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def start_watching_memory():
    """Register memory profiling tools to IPython instance."""
    global watching_memory

    # Just in case start is called more than once, stop watching. Hence unregister events
    stop_watching_memory()

    watching_memory = True
    ip = get_ipython()
    ip.events.register("post_run_cell", watch_memory)
    ip.events.register("pre_run_cell", pre_run_cell) 
开发者ID:ianozsvald,项目名称:ipython_memory_usage,代码行数:13,代码来源:ipython_memory_usage.py

示例11: stop_watching_memory

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def stop_watching_memory():
    """Unregister memory profiling tools from IPython instance."""
    global watching_memory
    watching_memory = False
    ip = get_ipython()
    try:
        ip.events.unregister("post_run_cell", watch_memory)
    except ValueError:
        pass
    try:
        ip.events.unregister("pre_run_cell", pre_run_cell)
    except ValueError:
        pass 
开发者ID:ianozsvald,项目名称:ipython_memory_usage,代码行数:15,代码来源:ipython_memory_usage.py

示例12: start_watching_memory

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def start_watching_memory():
    """Register memory profiling tools to IPython instance."""
    global watching_memory
    watching_memory = True
    ip = get_ipython()
    ip.events.register("post_run_cell", watch_memory)
    ip.events.register("pre_run_cell", pre_run_cell) 
开发者ID:ianozsvald,项目名称:ipython_memory_usage,代码行数:9,代码来源:ipython_memory_usage_perf.py

示例13: _enable_data_resource_formatter

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def _enable_data_resource_formatter(enable):
    if 'IPython' not in sys.modules:
        # definitely not in IPython
        return
    from IPython import get_ipython
    ip = get_ipython()
    if ip is None:
        # still not in IPython
        return

    formatters = ip.display_formatter.formatters
    mimetype = "application/vnd.dataresource+json"

    if enable:
        if mimetype not in formatters:
            # define tableschema formatter
            from IPython.core.formatters import BaseFormatter

            class TableSchemaFormatter(BaseFormatter):
                print_method = '_repr_data_resource_'
                _return_type = (dict,)
            # register it:
            formatters[mimetype] = TableSchemaFormatter()
        # enable it if it's been disabled:
        formatters[mimetype].enabled = True
    else:
        # unregister tableschema mime-type
        if mimetype in formatters:
            formatters[mimetype].enabled = False 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:31,代码来源:printing.py

示例14: run_on

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def run_on(source, processes=1, buffer_size=16):
    """
    Runs the pipeline from the last call to run_on up to source in parallel on the given number of processes.

    Parameters
    ----------
    source : iterable
        An iterable over a number of datapoints.
    ṕrocesses : int
        The number of processes to run in parallel.
    buffer_size: int
        The size of the buffer, where the output of the processes is stored.

    Returns
    -------
    gen : generator
        A generator that yields the output of the given source.
    """
    try:
        from IPython import get_ipython
        if get_ipython() is not None:
            cfg = get_ipython().config
            if "IPKernelApp" in cfg.keys():
                warn("Multiprocessing might crash in iPython Notebooks")
    except ImportError:
        pass

    return ProcessManager(source, processes, buffer_size) 
开发者ID:FelixGruen,项目名称:tensorflow-u-net,代码行数:30,代码来源:helper.py

示例15: time_dense_solvers

# 需要导入模块: import IPython [as 别名]
# 或者: from IPython import get_ipython [as 别名]
def time_dense_solvers():
    instructions = {
        solver: "u = solve_qp(P_array, q, G_array, h, solver='%s')" % solver
        for solver in dense_solvers}
    print("\nDense solvers\n-------------")
    for solver, instr in instructions.items():
        print("%s: " % solver, end='')
        get_ipython().magic('timeit %s' % instr) 
开发者ID:stephane-caron,项目名称:qpsolvers,代码行数:10,代码来源:sparse_problem.py


注:本文中的IPython.get_ipython方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。