spyder IDE的ipython启动配置 [英] ipython startup config for spyder IDE

查看:118
本文介绍了spyder IDE的ipython启动配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to add a few imports to my IPython profile so that when I open a kernel in the Spyder IDE they're always loaded. Spyder has a Qt interface (I think??), so I (a) checked to make sure I was in the right directory for the profile using the ipython locate command in the terminal (OSX), and (b) placing the following code in my ipython_qtconsole_config.py file:

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错误.

But when I open a new window and type pd.__version__ I get the NameError: name 'pd' is not defined error.

如果从终端运行ipython qtconsole,我没有任何问题.

I don't have any problems if I run ipython qtconsole from the Terminal.

建议?

谢谢!

推荐答案

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

Whether Spyder uses a QT interface or not shouldn't be related to which of the IPython config files you want to modify. The one you chose to modify, ipython_qtconsole_config.py is the configuration file that is loaded when you launch IPython's QT console, such as with the command line command

user@system:~$ ipython qtconsole

(我需要更新pyzmq才能正常工作.)

(I needed to update pyzmq for this to work.)

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

If Spyder maintains a running IPython kernel and merely manages how to display that for you, then Spyder is probably just maintaining a regular IPython session, in which case you want your configuration settings to go into the file ipython_config.py at the same directory where you found ipython_qtconsole_config.py.

我对此的管理方式与您略有不同.在ipython_config.py里面,对我来说最上面的几行是这样的:

I manage this slightly differently than you do. Inside of ipython_config.py the top few lines for me look like this:

# 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,该名称是我创建的文件,用于保存要执行的任何内容/启动时加载.

What this does is to obtain the IPython configuration directory for me, add on the profile_default subdirectory, and then add on the name launch.py which is a file that I created just to hold anything I want to be executed/loaded upon startup.

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

For example, here's the first bit from my file 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

还有很多,可能是几十个辅助函数,我认为很酷的代码片段,只是想玩,等等.我还定义了一些随机生成的玩具数据集,例如NumPy数组和Pandas DataFrames,因此当我想使用一些一次性的Pandas语法或其他东西时,总是有一些玩具数据.

There's a lot more, probably dozens of helper functions, snippets of code I've thought are cool and just want to play with, etc. I also define some randomly generated toy data sets, like NumPy arrays and Pandas DataFrames, so that when I want to poke around with some one-off Pandas syntax or something, some toy data is always right there.

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

The other upside is that this factors out the custom imports, function definitions, etc. that I want loaded, so if I want the same things loaded for the notebook and/or the qt console, I can just add the same bit of code to exec the file launch.py and I can make changes in only launch.py without having to manually migrate them to each of the three configuration files.

我也没有注释一些不同的设置,尤其是对于普通的IPython和笔记本而言,因此配置文件之间存在着有意义的差异,只是不基于我要在启动时导入的模块而定.

I also uncomment a few of the different settings, especially for plain IPython and for the notebook, so the config files are meaningfully different from each other, just not based on what modules I want imported on start up.

这篇关于spyder IDE的ipython启动配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆