【问题标题】:ipython startup config for spyder IDEspyder IDE 的 ipython 启动配置
【发布时间】:2015-08-17 19:33:55
【问题描述】:

尝试将一些导入添加到我的 IPython 配置文件中,以便当我在 Spyder IDE 中打开内核时它们总是被加载。 Spyder 有一个 Qt 界面(我认为??),所以我(a)使用终端(OSX)中的ipython locate 命令检查以确保我位于配置文件的正确目录中,并且(b)放置以下我的ipython_qtconsole_config.py 文件中的代码:

c.IPythonQtConsoleApp.exec_lines = ["import pandas as pd", 
                                "pd.set_option('io.hdf.default_format', 'table')",
                                "pd.set_option('mode.chained_assignment','raise')",
                                "from __future__ import division, print_function"]

但是当我打开一个新窗口并输入 pd.__version__ 时,我得到了 NameError: name 'pd' is not defined 错误。

编辑:如果我从终端运行ipython qtconsole,我没有任何问题。

建议?

谢谢!

【问题讨论】:

    标签: python ipython spyder


    【解决方案1】:

    Spyder 是否使用 QT 接口与您要修改哪个 IPython 配置文件无关。您选择修改的ipython_qtconsole_config.py 是您启动IPython 的 QT 控制台时加载的配置文件,例如使用命令行命令

    user@system:~$ ipython qtconsole
    

    (我需要更新 pyzmq 才能使其正常工作。)

    如果 Spyder 维护一个正在运行的 IPython 内核并且只管理如何为您显示它,那么 Spyder 可能只是维护一个常规的 IPython 会话,在这种情况下,您希望您的配置设置进入在您找到 ipython_qtconsole_config.py 的同一目录中的文件 ipython_config.py

    我的处理方式与你略有不同。在ipython_config.py 内部,对我来说,前几行如下所示:

    # Configuration file for ipython.
    from os.path import join as pjoin
    from IPython.utils.path import get_ipython_dir
    
    c = get_config()
    c.InteractiveShellApp.exec_files = [
        pjoin(get_ipython_dir(), "profile_default", "launch.py")
    ]
    

    它的作用是为我获取 IPython 配置目录,添加 profile_default 子目录,然后添加名称 launch.py 这是我创建的一个文件,只是为了保存我想要执行的任何内容/启动时加载。

    例如,这是我的文件launch.py 中的第一位:

    """
    IPython launch script
    Author: Ely M. Spears
    """
    
    import re
    import os
    import abc
    import sys
    import mock
    import time
    import types
    import pandas
    import inspect
    import cPickle
    import unittest
    import operator
    import warnings
    import datetime
    import dateutil
    import calendar
    import copy_reg
    import itertools
    import contextlib
    import collections
    import numpy as np
    import scipy as sp
    import scipy.stats as st
    import scipy.weave as weave
    import multiprocessing as mp
    from IPython.core.magic import (
        Magics,
        register_line_magic,
        register_cell_magic,
        register_line_cell_magic
    )
    from dateutil.relativedelta import relativedelta as drr
    
    
    ###########################
    # Pickle/Unpickle methods #
    ###########################
    
    # See explanation at:
    # < http://bytes.com/topic/python/answers/
    #   552476-why-cant-you-pickle-instancemethods >
    def _pickle_method(method):
        func_name = method.im_func.__name__
        obj = method.im_self
        cls = method.im_class
        return _unpickle_method, (func_name, obj, cls)
    
    def _unpickle_method(func_name, obj, cls):
        for cls in cls.mro():
            try:
                func = cls.__dict__[func_name]
            except KeyError:
                pass
            else:
                break
        return func.__get__(obj, cls)
    
    copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)
    
    #############
    # Utilities #
    #############
    def interface_methods(*methods):
        """
        Class decorator that can decorate an abstract base class with method names
        that must be checked in order for isinstance or issubclass to return True.
        """
        def decorator(Base):
            def __subclasshook__(Class, Subclass):
                if Class is Base:
                    all_ancestor_attrs = [ancestor_class.__dict__.keys()
                                          for ancestor_class in Subclass.__mro__]
                    if all(method in all_ancestor_attrs for method in methods):
                        return True
                return NotImplemented
            Base.__subclasshook__ = classmethod(__subclasshook__)
            return Base
    
    def interface(*attributes):
        """
        Class decorator checking for any kind of attributes, not just methods.
    
        Usage:
    
        @interface(('foo', 'bar', 'baz))
        class Blah
           pass
    
        Now, new classes will be treated as if they are subclasses of Blah, and 
        instances will be treated instances of Blah, provided they possess the
        attributes 'foo', 'bar', and 'baz'.
        """
        def decorator(Base):
            def checker(Other):
                return all(hasattr(Other, a) for a in attributes)
    
            def __subclasshook__(cls, Other):
                if checker(Other):
                    return True
                return NotImplemented
    
            def __instancecheck__(cls, Other):
                return checker(Other)
    
            Base.__metaclass__.__subclasshook__ = classmethod(__subclasshook__)
            Base.__metaclass__.__instancecheck__ = classmethod(__instancecheck__)
            return Base
        return decorator
    

    还有很多,可能有几十个辅助函数,sn-ps 的代码我觉得很酷,只是想玩,等等。我还定义了一些随机生成的玩具数据集,比如 NumPy 数组和 Pandas DataFrames ,所以当我想用一些一次性的 Pandas 语法或其他东西时,一些玩具数据总是在那里。

    另一个好处是这会排除我想要加载的自定义导入、函数定义等,所以如果我想要为笔记本和/或 qt 控制台加载相同的内容,我可以添加相同的位执行文件 launch.py 的代码,我可以在 only launch.py 中进行更改,而无需手动将它们迁移到三个配置文件中的每一个。

    我还取消了一些不同设置的注释,尤其是对于普通 IPython 和笔记本,因此配置文件彼此之间存在显着差异,只是不是基于我希望在启动时导入的模块。

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 2015-05-15
      • 2017-12-10
      • 1970-01-01
      • 2014-09-25
      • 2021-11-29
      • 2015-11-16
      • 2018-04-30
      • 2016-11-30
      相关资源
      最近更新 更多