【python】IPython的使用技巧整理

2023-11-04

IPython是一种基于Python的交互式解释器,提供了强大的编辑和交互功能。

IPython拥有:

  1. 满足你各种需求的交互式shell
  2. 火爆数据科学社区的Jupyter内核(供Jupyter Notebook使用)
  3. 对交互式数据可视化和GUI工具的完美支持
  4. 简单易用的高性能并行计算工具

 在电脑完成ipython安装或安装anaconda/miniconda的前提下,可以在命令行窗口输入ipython或直接打开Spyder工具即可打开Ipython运行环境。

 IPython中的‘I’即代表交互的意思,所以IPython提供了丰富的工具,能更好地与python进行交互。
大家经常遇到的魔法命令,就是IPython的众多功能之一。

0.  %quickref查看参考

%quickref用来查看IPython的特定语法和魔法命令参考。

%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")

Remember: TAB completion works in many contexts, not just file names
or python names.

The following magic functions are currently available:

%aimport:
    %aimport => Import modules for automatic reloading.
%alias:
    Define an alias for a system command.
%alias_magic:
    ::
%autoawait:
    
%autocall:
    Make functions callable without having to type parentheses.
%automagic:
    Make magic functions callable without having to type the initial %.
%autoreload:
    %autoreload => Reload modules automatically
%autosave:
    Set the autosave interval in the notebook (in seconds).
%bookmark:
    Manage IPython's bookmark system.
%cd:
    Change the current working directory.
%clear:
    Clear the terminal.
%cls:
    Clear the terminal.
%colors:
    Switch color scheme for prompts, info system and exception handlers.
%conda:
    Run the conda package manager within the current kernel.
%config:
    configure IPython
%connect_info:
    Print information for connecting other clients to this kernel
%copy:
    Alias for `!copy`
%ddir:
    Alias for `!dir /ad /on`
%debug:
    ::
%dhist:
    Print your history of visited directories.
%dirs:
    Return the current directory stack.
%doctest_mode:
    Toggle doctest mode on and off.
%echo:
    Alias for `!echo`
%ed:
    Alias for `%edit`.
%edit:
    Bring up an editor and execute the resulting code.
%env:
    Get, set, or list environment variables.
%gui:
    Enable or disable IPython GUI event loop integration.
%hist:
    Alias for `%history`.
%history:
    ::
%killbgscripts:
    Kill all BG processes started by %%script and its family.
%ldir:
    Alias for `!dir /ad /on`
%less:
    Show a file through the pager.
%load:
    Load code into the current frontend.
%load_ext:
    Load an IPython extension by its module name.
%loadpy:
    Alias of `%load`
%logoff:
    Temporarily stop logging.
%logon:
    Restart logging.
%logstart:
    Start logging anywhere in a session.
%logstate:
    Print the status of the logging system.
%logstop:
    Fully stop logging and close log file.
%ls:
    Alias for `!dir /on`
%lsmagic:
    List currently available magic functions.
%macro:
    Define a macro for future re-execution. It accepts ranges of history,
%magic:
    Print information about the magic function system.
%matplotlib:
    ::
%mkdir:
    Alias for `!mkdir`
%more:
    Show a file through the pager.
%notebook:
    ::
%page:
    Pretty print the object and display it through a pager.
%pastebin:
    Upload code to dpaste's paste bin, returning the URL.
%pdb:
    Control the automatic calling of the pdb interactive debugger.
%pdef:
    Print the call signature for any callable object.
%pdoc:
    Print the docstring for an object.
%pfile:
    Print (or run through pager) the file where an object is defined.
%pinfo:
    Provide detailed information about an object.
%pinfo2:
    Provide extra detailed information about an object.
%pip:
    Run the pip package manager within the current kernel.
%popd:
    Change to directory popped off the top of the stack.
%pprint:
    Toggle pretty printing on/off.
%precision:
    Set floating point precision for pretty printing.
%prun:
    Run a statement through the python code profiler.
%psearch:
    Search for object in namespaces by wildcard.
%psource:
    Print (or run through pager) the source code for an object.
%pushd:
    Place the current dir on stack and change directory.
%pwd:
    Return the current working directory path.
%pycat:
    Show a syntax-highlighted file through a pager.
%pylab:
    ::
%qtconsole:
    Open a qtconsole connected to this kernel.
%quickref:
    Show a quick reference sheet 
%recall:
    Repeat a command, or get command to input line for editing.
%rehashx:
    Update the alias table with all executable files in $PATH.
%reload_ext:
    Reload an IPython extension by its module name.
%ren:
    Alias for `!ren`
%rep:
    Alias for `%recall`.
%rerun:
    Re-run previous input
%reset:
    Resets the namespace by removing all names defined by the user, if
%reset_selective:
    Resets the namespace by removing names defined by the user.
%rmdir:
    Alias for `!rmdir`
%run:
    Run the named file inside IPython as a program.
%save:
    Save a set of lines or a macro to a given filename.
%sc:
    Shell capture - run shell command and capture output (DEPRECATED use !).
%set_env:
    Set environment variables.  Assumptions are that either "val" is a
%store:
    Lightweight persistence for python variables.
%sx:
    Shell execute - run shell command and capture output (!! is short-hand).
%system:
    Shell execute - run shell command and capture output (!! is short-hand).
%tb:
    Print the last traceback.
%time:
    Time execution of a Python statement or expression.
%timeit:
    Time execution of a Python statement or expression
%unalias:
    Remove an alias
%unload_ext:
    Unload an IPython extension by its module name.
%varexp:
    
%who:
    Print all interactive variables, with some minimal formatting.
%who_ls:
    Return a sorted list of all interactive variables.
%whos:
    Like %who, but gives some extra information about each variable.
%xdel:
    Delete a variable, trying to clear it from anywhere that
%xmode:
    Switch modes for the exception handlers.
%%!:
    Shell execute - run shell command and capture output (!! is short-hand).
%%HTML:
    Alias for `%%html`.
%%SVG:
    Alias for `%%svg`.
%%bash:
    %%bash script magic
%%capture:
    ::
%%cmd:
    %%cmd script magic
%%debug:
    ::
%%file:
    Alias for `%%writefile`.
%%html:
    ::
%%javascript:
    Run the cell block of Javascript code
%%js:
    Run the cell block of Javascript code
%%latex:
    Render the cell as a block of latex
%%markdown:
    Render the cell as Markdown text block
%%perl:
    %%perl script magic
%%prun:
    Run a statement through the python code profiler.
%%pypy:
    %%pypy script magic
%%python:
    %%python script magic
%%python2:
    %%python2 script magic
%%python3:
    %%python3 script magic
%%ruby:
    %%ruby script magic
%%script:
    ::
%%sh:
    %%sh script magic
%%svg:
    Render the cell as an SVG literal
%%sx:
    Shell execute - run shell command and capture output (!! is short-hand).
%%system:
    Shell execute - run shell command and capture output (!! is short-hand).
%%time:
    Time execution of a Python statement or expression.
%%timeit:
    Time execution of a Python statement or expression
%%writefile:
    ::

1. ?打印IPython简介

2. object ?内省功能

3. object ??内省功能

???功能相似,不过??还可以查看函数或模块对象的源代码。

4. history历史命令

在IPython中,执行historyhist命令能够查看历史输入。

5. tab自动补全

 IPython支持tab键自动补全。

6. ! shell_command执行shell命令

shell (windows里叫作cmd)表示使用文本与计算机进行交互的方式,在IPython中,shell命令前加上感叹号!(英文输入法)就可以直接执行。 如图使用ping检测百度网址。 

7. 魔法命令%和%%区别

魔法命令分为两种,一种是line magics,另外一种cell magics。 Line magic是通过在前面加%,表示magic只在本行有效。 Cell magic是通过在前面加%%,表示magic在整个cell单元有效。

7.1 %run运行脚本

在IPython会话环境中,py文件可以通过%run命令当做Python程序来运行,输入%run 路径+文件名称即可。

7.2 %run -d交互式调试器

%run -d用于对脚本进行调试。

7.3 %load加载代码

%load命令用于将脚本代码加载到当前cell。

 7.4 %debug交互式调试器

%debug命令支持从最新的异常跟踪的底部进入交互式调试器。 在ipdb调试模式下能访问所有的本地变量和整个栈回溯。使用u和d向上和向下访问栈,使用q退出调试器。在调试器中输入?可以查看所有的可用命令列表。

7.5 %pdb交互式调试器

%pdb同样用于启动交互式调试器,不过支持对所有的异常进行调试。你需要事先启动%pdb命令,之后对每一个异常都会进行调试。

 7.6 %macro定义宏

%macro taskname n1 n2...用来定义宏,并给宏命名,执行指定的代码行。 执行name就是执行n1 n2...这些代码。

7.7 %timeit测量运行时间

IPython使用魔法命令%timeit来测量单行代码的运行时间。

7.8 %%timeit测量代码运行时间

%%timeit用来测量整个单元格代码的运行时间.

7.9 %env环境变量

%env命令用于显示环境变量。 

 7.10 %pycat语法高亮

%pycat filename用语法高亮显示一个python文件(不用加.py后缀名)。

7.11 %pdef打印构造信息

%pdef命令用来打印类、函数的构造信息。

7.12 %pdoc打印文档

%pdoc命令用来打印对象的文档字符串。

7.13 %precision浮点数精度

%precision命令用来设置浮点数精度,可添加具体参数,无参数则默认精度。

7.14 %xdel删除变量

%xdel命令用于删除变量,并尝试清楚其在IPython中的对象上的一切引用。

7.15 %who显示变量

%who命令用于显示当前所有变量,你也可以指定显示变量的类型。

7.16  %whos显示变量

%whos命令同样用于显示当前变量,但提供的信息更加丰富。

7.17 %save保存cell

%save path n1 n2..命令用于将指定cell代码保存到指定的py文件中。

7.18 %pwd显示工作路径

该魔法命令用来显示当前工作目录的路径。 

7.19 %ls显示目录内容

7.20 %cd修改目录

7.21 %matplotlib inline显示图像

在notebook中绘制图像时,使用%matplotlib inline命令可以将图表直接嵌入到notebook中,方便查看。 

7.22 %pylab交互式计算

%pylab 魔法命令可以使numpy和matplotlib中的科学计算功能生效,这些功能被称为基于向量和矩阵的高效操作,交互可视化特性。它能够让我们在控制台进行交互式计算和动态绘图。 

7.23 %conda安装第三方库

%conda install pkgs命令用于在IPython中安装python第三方库。

不建议在IPython内直接安装python第三方库,容易卡死python内核。

7.24 %notebook导出notebook

%notebook path用于导出当前notebook内容到指定ipynb文件中。

8. 通配符*

使用通配符*?可以模糊查询方法名及属性。

9. _打印前输出结果

使用一个下划线 _ 获取前一个输出结果,它是个变量,实时更新的。 使用两个下划线 __可以获取倒数第二个输出,使用三个下划线 ___ 获取倒数第三个输出(没有输出的命令行不计入在内,只支持前三个输出结果)。

10. ;抑制输出

在语句后面加上;,不显示输出结果。

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【python】IPython的使用技巧整理 的相关文章

随机推荐

  • Android webView去除默认边框

    Android WebView无论怎么修改它的属性都会存在一定的边距 这是因为 HTML 的 body 标签默认存在一定边距 修改 webView 的属性并没有作用 解决办法 修改 html 代码 html data 原本需要加载的html
  • KaTeX

    KaTeX LaTeX数学公式编辑手册 只需要在第三列写法前后分别加上 就可以转换为符号 但需注意 CSDN的使用的是 KaTeX KaTeX KATE X数学公式 而不是 LaTeX LaTeX LATE X 两者会有些许区别 如果有
  • 漂亮的计算器页面 html,html+css实现一个好看的计算器实例代码

    最终效果如下图 2 有bug 就是整数后点击 号结果正确 如果小数后面点击 的话结果就错误 其他都正常 求指点 input的value是string类型的 在JS中改如何正确处理下图 1中的if部分 图 1 图 2 HTML代码如下 简单的
  • 【超全汇总】学习数据结构与算法,计算机基础知识,看这篇就够了

    由于文章有点多 并且发的文章也不是一个系列一个系列发的 不过我的文章大部分都是围绕着 数据结构 算法 计算机网络 操作系统 Linux 数据库 这几个方面发的 为了方便大家阅读 我整理了一波 不过公众号可以说是不支持修改文章 因为我决定每两
  • Java环境从删除到重装

    Java环境从删除到重装 前言 须知 如何完全删除jdk 安装jdk 前言 今天由于一些原因把Java环境删除了 怎么装都装不好 遇到了很多错误 在网上找了好多解决办法之后终于弄好了 所以写成一份Java环境从删除到重装 给各位不小心删除J
  • Centos7下基于jdk11 安装RocketMQ

    1 简介 RocketMQ是阿里巴巴中间件团队自研的一款高性能 高吞吐量 低延迟 高可用 高可靠 具备金融级稳定性 的分布式消息中间件 开源后并于2016年捐赠给Apache社区孵化 目前已经成为了 Apache顶级项目 当前在国内被广泛的
  • 用html+js实现代码背景墙特效【建议收藏】

    在csdn里面 有些博主的主页非常的帅 就是代码从上往下掉的特效 那么这种效果我们作为程序员该如何去写出来呢 不用担心 这篇博客就分享如何创建一个代码背景墙 1 效果展示 2 代码分享
  • java.io.FileNotFoundException: http://www.xxxxx.net:8080/test/test/ 403错误

    POST请求错误内容 java io FileNotFoundException http www xxxxx net 8080 test test at libcore net http HttpURLConnectionImpl get
  • python 中的六种“复制”方法

    以列表为例 方法一 直接变量赋值 将 li 赋值给变量 li1 打印他们的id会发现 他们的id是一样的 即是 li 和 li1 这两个变量在python中是同一个内存地址 对他们任何一个变量进行修改 另外一个会跟着变化 li 1 2 3
  • arm体系结构概述和编程模型

    1 arm体系结构的版本 1 arm1 6 2 arm体系的变种 1 T 系列 Thumb指令集 可以支持Thumb指令集 2 M系列 支持长乘法 32位 32位生成64位数据 长乘加指令 再加上32位数据 3 E系列 增强型DSP指令 增
  • 【Go语言(golang)教程】A Tour of Go 七十集大全

    http www aqee net go a tour of go 5 Go语言 golang 教程 A Tour of Go 1 Hello World Go语言 golang 教程 A Tour of Go 2 安装离线练习器 Go语言
  • 数字电子钟 1Hz 秒脉冲信号的设计

    数字电子钟 1Hz 秒脉冲信号的设计 摘 要 要设计数字钟 首先应选择一个能产生稳定的标准时间脉冲信号 而脉冲源产生的脉冲信号的频率较高 因此 需要进行分频 使高频脉冲信号变成适合于计时的低频脉冲信号 即 秒脉冲信号 频率1HZ 1引言 数
  • 找出看了5个电影以上的用户

    问题 在1亿条用户记录里 如何快速查询统计出看了5个电影以上的用户 解答 分以下几个步骤完成 1 建立 hash map lt 用户 电影数 gt 2 顺序扫描1亿条用户记录 1 如果 用户 在hash map中不存在 则新增并设 电影数
  • IT项目管理之第5章 项目时间管理习题之案例分析汇总

    IT项目管理之第5章 项目时间管理习题之案例分析汇总 项目时间管理习题之案例分析汇总 案例1 案例分析 案例1参考答案 案例2 案例2分析 案例2参考答案 叮嘟 这里是小啊呜的学习课程资料整理 好记性不如烂笔头 今天也是努力进步的一天 一起
  • DevopsCamp 第 2 期作业: 《cobra - 05 Go 项目的目录结构》

    DevopsCamp 第 2 期作业 cobra 05 Go 项目的目录结构 原文链接 https typonotes com posts 2023 02 13 devopscamp cobra 05 layout Go 项目的目录结构 G
  • windows server 2016搭建AD域

    此实验以windows sever 2016为例 安装windows server 2016 操作省略 一台服务器想要安装成AD DC 活动目录域服务 必须具备以下条件 安装者必须具有本地管理员权限 DNS基础结构的支持 可以在安装AD D
  • 电脑开机出现黑屏,出现“windows 未能启动,原因可能更改了硬件或者软件,解决此类问题的步骤”

    出现问题的界面如下 解决此类问题的步骤如下 1 直接按 enter 回车键 2 出现以下界面 我自己的是windows 10系统哈 因为当时没保存自己的照片 只能拿这个顶替一下 但是步骤是一样的 3 然后按提示按F8 正常来说时会出现以下的
  • Python高级函数2:使用itertools、functools、operator使得代码更高效、可读、可重用

    Python高级函数2 使用itertools functools operator使得代码更高效 可读 可重用 1 原理 itertools groupby functools partial operator attrgetter 和
  • python生成gif(图片渐变)

    show you the code 后面还需要完善图片分辨率的处理 这样就比较好了 目前分辨率没有进行处理 import os import imageio from PIL import Image from images2gif imp
  • 【python】IPython的使用技巧整理

    IPython是一种基于Python的交互式解释器 提供了强大的编辑和交互功能 IPython拥有 满足你各种需求的交互式shell 火爆数据科学社区的Jupyter内核 供Jupyter Notebook使用 对交互式数据可视化和GUI工