Skip to content

IPython的安装与使用

1584字约5分钟

PythonIPython

2024-07-09

IPython 安装与使用

IPython 提供了丰富的工具包,帮助您充分利用 Python 的交互功能。其主要组件包括:

  • 一个强大的交互式 Python shell

    image-20240709093656901

  • Jupyter 内核用于处理 Jupyter 笔记本和其他交互式前端中的 Python 代码。

安装

通过 pip 命令能够快速的安装 ipython,命令如下:

# 从pypi.org 安装较慢,这里建议使用国内镜像源
pip install ipython -i https://pypi.tuna.tsinghua.edu.cn/simple

安装 ipython 完成后,终端输入 ipython 即可进入交互环境。

image-20240709095241303

使用 ipython 时,发现了如下报错:

image-20240709095045728

这个问题的原因是 Python3.8Windows 上默认事件循环更改为了 ProactorEventLoop,而非 SelectorEventLoop,因此会存在一些问题,执行如下代码,能够处理这个报错。

import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
loop = asyncio.get_event_loop()

image-20240709095549051

此外,ipython 已经集成到 Jupyter 项目中,因此安装 Jupyter 也可以使用 ipython ,安装 Anaconda 也可以通过 Jupyter 使用 ipython

image-20240709095844248

使用

ipython 通过从 shell 发出命令来启动 IPython,启动后会有如下内容:

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.12.3 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

四个最有用的命令

命令描述
介绍 IPython 以及它的特性
%quickref快速引用
helpPython 自身的帮助信息
object?对象的介绍,方法以及使用文档

如下是以上四个命令的具体执行:

  • ?,介绍 IPython 以及帮助文档、使用方法等。

    In [1]: ?
    
    IPython -- An enhanced Interactive Python
    =========================================
    
    IPython offers a fully compatible replacement for the standard Python
    interpreter, with convenient shell features, special commands, command
    history mechanism and output results caching.
    
    At your system command line, type 'ipython -h' to see the command line
    options available. This document only describes interactive features.
    
    GETTING HELP
    ------------
                                         
    Within IPython you have various way to access help:
    
      ?         -> Introduction and overview of IPython's features (this screen).
      object?   -> Details about 'object'.
      object??  -> More detailed, verbose information about 'object'.
      %quickref -> Quick reference of all IPython specific syntax and magics.
      help      -> Access Python's own help system.
    
    If you are in terminal IPython you can quit this screen by pressing `q`.
    ...
  • %quickref,显示 IPython 常用功能和命令的快速参考。

    In [1]: %quickref
    
    IPython -- An enhanced Interactive Python - Quick Reference Card
    ================================================================
    
    obj?, obj??      : Get help, or more help for object (also works as
                       ?obj, ??obj).
    ?foo.*abc*       : List names in 'foo' containing 'abc' in them.
    %magic           : Information about IPython's 'magic' % functions.
    
    Magic functions are prefixed by % or %%, and typically take their arguments
    without parentheses, quotes or even commas for convenience.  Line magics take a
    single % and cell magics are prefixed with two %%.
    
    Example magic function calls:        
    
    %alias d ls -F   : 'd' is now an alias for 'ls -F'
    alias d ls -F    : Works if 'alias' not a python name
    alist = %alias   : Get list of aliases to 'alist'
    cd /usr/share    : Obvious. cd -<tab> to choose from visited dirs.
    %cd??            : See help AND source for magic %cd
    %timeit x=10     : time the 'x=10' statement with high precision.
    %%timeit x=2**100
    x**100           : time 'x**100' with a setup of 'x=2**100'; setup code is not
                       counted.  This is an example of a cell magic.
    
    System commands:
                                         
    !cp a.txt b/     : System command escape, calls os.system()
    cp a.txt b/      : after %rehashx, most system commands work without !
    cp ${f}.txt $bar : Variable expansion in magics and system commands
    files = !ls /usr : Capture system command output
    files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
    
    History:
    
    _i, _ii, _iii    : Previous, next previous, next next previous input
    _i4, _ih[2:5]    : Input history line 4, lines 2-4
    exec(_i81)       : Execute input history line #81 again
    %rep 81          : Edit input history line #81
    _, __, ___       : previous, next previous, next next previous output
    _dh              : Directory history
    _oh              : Output history
    %hist            : Command history of current session.
    %hist -g foo     : Search command history of (almost) all sessions for 'foo'.
    %hist -g         : Command history of (almost) all sessions.
    %hist 1/2-8      : Command history containing lines 2-8 of session 1.
    %hist 1/ ~2/     : Command history of session 1 and 2 sessions before current.
    %hist ~8/1-~6/5  : Command history from line 1 of 8 sessions ago to
                       line 5 of 6 sessions ago.
    %edit 0/         : Open editor to execute code with history of current session.
    
    Autocall:
                                         
    f 1,2            : f(1,2)  # Off by default, enable with %autocall magic.
    /f 1,2           : f(1,2) (forced autoparen)
    ,f 1 2           : f("1","2")
    ;f 1 2           : f("1 2")
    ...
  • help()Python 自身的帮助文档。

    In [7]: help()
    
    Welcome to Python 3.8's help utility!
    
    If this is your first time using Python, you should definitely check out
    the tutorial on the Internet at https://docs.python.org/3.8/tutorial/.
    
    Enter the name of any module, keyword, or topic to get help on writing
    Python programs and using Python modules.  To quit this help utility and
    return to the interpreter, just type "quit".
    
    To get a list of available modules, keywords, symbols, or topics, type
    "modules", "keywords", "symbols", or "topics".  Each module also comes
    with a one-line summary of what it does; to list the modules whose name
    or summary contain a given string such as "spam", type "modules spam".
    
    help> os
    Help on module os:                                                                                                                                             
    
    NAME
        os - OS routines for NT or Posix depending on what system we're on.
    
    DESCRIPTION
        This exports:
          - all functions from posix or nt, e.g. unlink, stat, etc.
          - os.path is either posixpath or ntpath
          - os.name is either 'posix' or 'nt'
          - os.curdir is a string representing the current directory (always '.')
          - os.pardir is a string representing the parent directory (always '..')
          - os.sep is the (or a most common) pathname separator ('/' or '\\')
    ...
  • object?,对象的属性和方法文档。

    In [1]: import os
    
    In [2]: os?
    Type:        module
    String form: <module 'os' from 'D:\\Enviroment\\Python38\\lib\\os.py'>
    File:        d:\enviroment\python38\lib\os.py
    Docstring:
    OS routines for NT or Posix depending on what system we're on.
    
    This exports:
      - all functions from posix or nt, e.g. unlink, stat, etc.
      - os.path is either posixpath or ntpath
      - os.name is either 'posix' or 'nt'
      - os.curdir is a string representing the current directory (always '.')
      - os.pardir is a string representing the parent directory (always '..')
      - os.sep is the (or a most common) pathname separator ('/' or '\\')
    ...

Tab 补全

使用 Tab 按键,即可查看对象的属性,除了 Python 的对象和关键字以外 Tan 补全还适用于文件和目录名称。

  • 对象属性补全

    image-20240709101245271

  • 文件和目录名称补全

    image-20240709101649844

系统 shell 命令

要运行系统 shell 中的命令,只需要在前面加上 !,例如:

In [1]: !ping www.baidu.com

正在 Ping www.a.shifen.com [220.181.38.149] 具有 32 字节的数据:
来自 220.181.38.149 的回复: 字节=32 时间=26ms TTL=52
来自 220.181.38.149 的回复: 字节=32 时间=32ms TTL=52
来自 220.181.38.149 的回复: 字节=32 时间=23ms TTL=52
来自 220.181.38.149 的回复: 字节=32 时间=23ms TTL=52

220.181.38.149 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 23ms,最长 = 32ms,平均 = 26ms

启动文件

将启动要执行的文件放置到 ~/./IPython/profile_default/startup目录下,这里准备一个 env_setup.py 更改事件循环的方式,代码如下:

import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
loop = asyncio.get_event_loop()
print("事件循环方式已更改~")

再次执行 ipython 进入终端环境,env_setup.py 文件正常被执行。

(.venv) PS D:\Code\Python\PythonBase> ipython
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.12.3 -- An enhanced Interactive Python. Type '?' for help.
事件循环方式已更改~

In [1]: