标签归档:ipython

使用IPython进行分步调试

问题:使用IPython进行分步调试

根据我的阅读,有两种方法可以在Python中调试代码:

  • 使用传统的调试器,例如pdbipdb。它支持诸如cfor continuenfor step-oversfor step-into等命令,但是您没有直接访问IPython shell的权限,这对于对象检查非常有用。

  • 通过 IPython shell 嵌入代码中来使用 IPython。您可以这样做,然后在您的代码中使用。当您的程序/脚本命中一条语句时,您将进入IPython shell。这允许使用所有IPython好东西对对象进行全面检查并测试Python代码。但是,在使用时,您将无法通过便捷的键盘快捷键逐步完成代码。from ipython import embedembed()embed()embed()

有什么办法可以融合两全其美?即

  1. 能够 使用方便的pdb / ipdb键盘快捷键逐步完成代码。
  2. 在任何这样的步骤(例如,在给定的语句上),都可以访问成熟的IPython shell

如在 MATLAB中一样进行 IPython调试:

在MATLAB中可以找到这种“增强调试”类型的示例,在该示例中,用户始终可以完全访问MATLAB引擎/外壳,并且她仍然可以逐步完成代码,定义条件断点等。我已经与其他用户讨论过,这是人们从MATLAB转移到IPython时最想念的调试功能。

在Emacs和其他编辑器中进行IPython调试:

我不想让这个问题过于具体,但是我主要在Emacs中工作,所以我想知道是否有任何方法可以将此功能引入其中。理想情况下,Emacs(或编辑器)将允许程序员在代码上的任意位置设置断点,并与解释器或调试器进行通信,以使其在您选择的位置停止,并在该位置提供完整的IPython解释器。

From what I have read, there are two ways to debug code in Python:

  • With a traditional debugger such as pdb or ipdb. This supports commands such as c for continue, n for step-over, s for step-into etc.), but you don’t have direct access to an IPython shell which can be extremely useful for object inspection.

  • Using IPython by embedding an IPython shell in your code. You can do from IPython import embed, and then use embed() in your code. When your program/script hits an embed() statement, you are dropped into an IPython shell. This allows the full inspection of objects and testing of Python code using all the IPython goodies. However, when using embed() you can’t step-by-step through the code anymore with handy keyboard shortcuts.

Is there any way to combine the best of both worlds? I.e.

  1. Be able to step-by-step through your code with handy pdb/ipdb keyboard shortcuts.
  2. At any such step (e.g. on a given statement), have access to a full-fledged IPython shell.

IPython debugging as in MATLAB:

An example of this type of “enhanced debugging” can be found in MATLAB, where the user always has full access to the MATLAB engine/shell, and she can still step-by-step through her code, define conditional breakpoints, etc. From what I have discussed with other users, this is the debugging feature that people miss the most when moving from MATLAB to IPython.

IPython debugging in Emacs and other editors:

I don’t want to make the question too specific, but I work mostly in Emacs, so I wonder if there is any way to bring this functionality into it. Ideally, Emacs (or the editor) would allow the programmer to set breakpoints anywhere on the code and communicate with the interpreter or debugger to have it stop in the location of your choice, and bring to a full IPython interpreter on that location.


回答 0

您可以使用IPython的%pdb魔力。只需调用%pdbIPython,当发生错误时,您会自动转到ipdb。虽然您没有立即迈出一步,但您ipdb之后就进入了。

这使调试单个函数变得容易,因为您可以使用加载文件%load然后运行一个函数。您可以assert在正确的位置使用来强制执行错误。

%pdb是线魔术。呼之为%pdb on%pdb 1%pdb off%pdb 0。如果在不带参数的情况下调用它,则它将作为切换。

You can use IPython’s %pdb magic. Just call %pdb in IPython and when an error occurs, you’re automatically dropped to ipdb. While you don’t have the stepping immediately, you’re in ipdb afterwards.

This makes debugging individual functions easy, as you can just load a file with %load and then run a function. You could force an error with an assert at the right position.

%pdb is a line magic. Call it as %pdb on, %pdb 1, %pdb off or %pdb 0. If called without argument it works as a toggle.


回答 1

ipdb.set_trace()呢?在您的代码中:

import ipdb; ipdb.set_trace()

更新:现在在Python 3.7中,我们可以编写breakpoint()。它的工作原理相同,但也遵守PYTHONBREAKPOINT环境变量。此功能来自此PEP

这样可以对代码进行全面检查,并且您可以访问诸如c(继续),n(执行下一行),s(进入当前方法)之类的命令。

请参阅ipdb repo命令列表IPython现在称为Jupyter(的一部分)。


ps:请注意,ipdb命令优先于python代码。所以为了写,list(foo)你需要print list(foo)

另外,如果您喜欢ipython提示符(它的emacs和vim模式,历史记录,完成情况等),由于它基于python提示符工具包,因此很容易为您的项目获得相同的名称。

What about ipdb.set_trace() ? In your code :

import ipdb; ipdb.set_trace()

update: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.

This allows for full inspection of your code, and you have access to commands such as c (continue), n (execute next line), s (step into the method at point) and so on.

See the ipdb repo and a list of commands. IPython is now called (edit: part of) Jupyter.


ps: note that an ipdb command takes precedence over python code. So in order to write list(foo) you’d need print(list(foo)), or !list(foo) .

Also, if you like the ipython prompt (its emacs and vim modes, history, completions,…) it’s easy to get the same for your project since it’s based on the python prompt toolkit.


回答 2

(2016年5月28日更新)在Emacs中使用RealGUD

对于Emacs中的任何人,此线程都说明了如何使用

  1. Emacs中一个称为RealGUD的新的重要调试器,可以与任何调试器(包括ipdb)一起使用。
  2. Emacs软件包isend-mode

这两个软件包的组合非常强大,可以使它们完全重新创建OP中描述的行为,甚至可以做更多的事情。

有关RealGUD for ipdb 的Wiki文章的更多信息。


原始答案:

在尝试了多种不同的调试Python方法(包括本线程中提到的所有内容)之后,我使用IPython调试Python的首选方法之一是使用嵌入式外壳程序。

定义定制的嵌入式IPython Shell:

将以下内容添加到脚本中PYTHONPATH,以使该方法ipsh()可用。

import inspect

# First import the embed function
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config

# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = '   .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '

# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")   
exit_msg = '**Leaving Nested interpreter'

# Wrap it in a function that gives me more context:
def ipsh():
    ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)

    frame = inspect.currentframe().f_back
    msg   = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)

    # Go back one level! 
    # This is needed because the call to ipshell is inside the function ipsh()
    ipshell(msg,stack_depth=2)

然后,每当我要调试代码中的某些内容时,就将其放置ipsh()在需要进行对象检查等的位置。例如,说我要在my_function下面调试

使用它:

def my_function(b):
  a = b
  ipsh() # <- This will embed a full-fledged IPython interpreter
  a = 4

然后my_function(2)以下列方式之一调用:

  1. 通过运行从Unix Shell调用此函数的Python程序
  2. 或直接从IPython调用

不管我如何调用它,解释器都会停在所说的行ipsh()。完成后,您可以执行操作Ctrl-D,Python将恢复执行(使用您所做的任何变量更新)。请注意,如果您从常规IPython IPython Shell(上面的案例2)运行代码,那么新的IPython Shell将嵌套在您从中调用它的外壳内,这很好,但是请注意。无论哪种方式,一旦解释器停在的位置ipsh,我都可以检查a2)的值,查看定义了哪些函数和对象,等等。

问题:

上面的解决方案可以使Python在代码中所需的任何位置停止,然后将您带入完整的IPython解释器。不幸的是,调用脚本后,它不允许您添加或删除断点,这非常令人沮丧。在我看来,这是阻止IPython成为Python出色的调试工具的唯一原因

您目前可以做的最好的事情是:

一种解决方法是ipsh()在要Python解释程序启动IPython Shell的不同位置(即breakpoint)放置先验先验。然后,您可以使用以下命令在不同的预定义,硬编码的“断点”之间“跳转”Ctrl-D,这将退出当前的嵌入式IPython shell,并且每当解释器单击下一个调用时再次停止ipsh()

如果走这条路线,退出“调试模式”并忽略所有后续断点的一种方法是使用ipshell.dummy_mode = True,这将使Python忽略ipshell我们在上面创建的对象的任何后续实例化。

(Update on May 28, 2016) Using RealGUD in Emacs

For anyone in Emacs, this thread shows how to accomplish everything described in the OP (and more) using

  1. a new important debugger in Emacs called RealGUD which can operate with any debugger (including ipdb).
  2. The Emacs package isend-mode.

The combination of these two packages is extremely powerful and allows one to recreate exactly the behavior described in the OP and do even more.

More info on the wiki article of RealGUD for ipdb.


Original answer:

After having tried many different methods for debugging Python, including everything mentioned in this thread, one of my preferred ways of debugging Python with IPython is with embedded shells.

Defining a custom embedded IPython shell:

Add the following on a script to your PYTHONPATH, so that the method ipsh() becomes available.

import inspect

# First import the embed function
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config

# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = '   .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '

# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")   
exit_msg = '**Leaving Nested interpreter'

# Wrap it in a function that gives me more context:
def ipsh():
    ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)

    frame = inspect.currentframe().f_back
    msg   = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)

    # Go back one level! 
    # This is needed because the call to ipshell is inside the function ipsh()
    ipshell(msg,stack_depth=2)

Then, whenever I want to debug something in my code, I place ipsh() right at the location where I need to do object inspection, etc. For example, say I want to debug my_function below

Using it:

def my_function(b):
  a = b
  ipsh() # <- This will embed a full-fledged IPython interpreter
  a = 4

and then I invoke my_function(2) in one of the following ways:

  1. Either by running a Python program that invokes this function from a Unix shell
  2. Or by invoking it directly from IPython

Regardless of how I invoke it, the interpreter stops at the line that says ipsh(). Once you are done, you can do Ctrl-D and Python will resume execution (with any variable updates that you made). Note that, if you run the code from a regular IPython the IPython shell (case 2 above), the new IPython shell will be nested inside the one from which you invoked it, which is perfectly fine, but it’s good to be aware of. Eitherway, once the interpreter stops on the location of ipsh, I can inspect the value of a (which be 2), see what functions and objects are defined, etc.

The problem:

The solution above can be used to have Python stop anywhere you want in your code, and then drop you into a fully-fledged IPython interpreter. Unfortunately it does not let you add or remove breakpoints once you invoke the script, which is highly frustrating. In my opinion, this is the only thing that is preventing IPython from becoming a great debugging tool for Python.

The best you can do for now:

A workaround is to place ipsh() a priori at the different locations where you want the Python interpreter to launch an IPython shell (i.e. a breakpoint). You can then “jump” between different pre-defined, hard-coded “breakpoints” with Ctrl-D, which would exit the current embedded IPython shell and stop again whenever the interpreter hits the next call to ipsh().

If you go this route, one way to exit “debugging mode” and ignore all subsequent breakpoints, is to use ipshell.dummy_mode = True which will make Python ignore any subsequent instantiations of the ipshell object that we created above.


回答 3

您可以从pudb启动IPython会话,然后根据需要返回调试会话。

顺便说一句,ipdb在幕后使用IPython,您实际上可以使用IPython功能,例如TAB完成和魔术命令(以开头的命令%)。如果你是IPDB OK,你可以从IPython中使用命令,如启动%run%debug。从某种意义上讲,ipdb会话实际上比普通的IPython会话要好,因为您可以在堆栈跟踪中上下移动。ipdb中“对象检查”缺少什么?

另外,与Emacs> = 24.3捆绑在一起的python.el具有不错的ipdb支持。

You can start IPython session from pudb and go back to the debugging session as you like.

BTW, ipdb is using IPython behind the scenes and you can actually use IPython functionality such as TAB completion and magic commands (the one starts with %). If you are OK with ipdb you can start it from IPython using commands such as %run and %debug. ipdb session is actually better than plain IPython one in the sense you can go up and down in the stack trace etc. What is missing in ipdb for “object inspection”?

Also, python.el bundled with Emacs >= 24.3 has nice ipdb support.


回答 4

似乎@gaborous的答案中的方法已被弃用

新方法似乎是:

from IPython.core import debugger
debug = debugger.Pdb().set_trace

def buggy_method():
    debug()

Looks like the approach in @gaborous’s answer is deprecated.

The new approach seems to be:

from IPython.core import debugger
debug = debugger.Pdb().set_trace

def buggy_method():
    debug()

回答 5

前缀“!” 在pdb中键入命令的符号似乎与在IPython shell中执行操作具有相同的效果。这适用于访问某些功能甚至变量名的帮助。也许这会对您有所帮助。例如,

ipdb> help(numpy.transpose)
*** No help on (numpy.transpose)

但是!help(numpy.transpose)将为您提供有关numpy.transpose的预期帮助页面。同样,对于变量名,假设您有一个变量l,在pdb中键入“ l”会列出代码,但是!l会打印出l的值。

Prefixing an “!” symbol to commands you type in pdb seems to have the same effect as doing something in an IPython shell. This works for accessing help for a certain function, or even variable names. Maybe this will help you to some extent. For example,

ipdb> help(numpy.transpose)
*** No help on (numpy.transpose)

But !help(numpy.transpose) will give you the expected help page on numpy.transpose. Similarly for variable names, say you have a variable l, typing “l” in pdb lists the code, but !l prints the value of l.


回答 6

您是否尝试过此技巧

或者更好的是,使用ipython并调用:

from IPython.Debugger import Tracer; debug_here = Tracer()

那你就可以用

debug_here()

每当你想设置一个断点

Did you try this tip?

Or better still, use ipython, and call:

from IPython.Debugger import Tracer; debug_here = Tracer()

then you can just use

debug_here()

whenever you want to set a breakpoint


回答 7

您可以IPython 从内部 开始ipdb

引入ipdb调试器1

import idpb; ipdb.set_trace()

输入IPython的从内部ipdb>控制台2

from IPython import embed; embed()

ipdb>从以下位置返回到控制台IPython

exit

如果您有幸使用Emacs,可以使事情变得更加便捷!

这需要使用M-x shell。使用yasnippetbm,定义以下代码段。这将用行替换ipdb编辑器中的文本set-trace。插入代码段后,该行将突出显示,以便易于观察和导航。使用M-x bm-next导航。

# -*- mode: snippet -*-
# name: ipdb
# key: ipdb
# expand-env: ((yas-after-exit-snippet-hook #'bm-toggle))
# --
import ipdb; ipdb.set_trace()

1全部一行,易于删除。由于imports仅发生一次,因此此表单确保ipdb将在您需要时将其导入,而不会产生额外的开销。

2,您可以通过导入自己节省一些打字IPython 的内.pdbrc文件

try:
    from IPython import embed
except:
    pass

这使您可以简单地embed()从内部进行调用ipdb(当然,仅在安装IPython时)。

You can start IPython from within ipdb!

Induce the ipdb debugger1:

import idpb; ipdb.set_trace()

Enter IPython from within in the ipdb> console2:

from IPython import embed; embed()

Return to the ipdb> console from within IPython:

exit

If you’re lucky enough to be using Emacs, things can be made even more convenient!

This requires using M-x shell. Using yasnippet and bm, define the following snippet. This will replace the text ipdb in the editor with the set-trace line. After inserting the snippet, the line will be highlighted so that it is easily noticeable and navigable. Use M-x bm-next to navigate.

# -*- mode: snippet -*-
# name: ipdb
# key: ipdb
# expand-env: ((yas-after-exit-snippet-hook #'bm-toggle))
# --
import ipdb; ipdb.set_trace()

1 All on one line for easy deletion. Since imports only happen once, this form ensures ipdb will be imported when you need it with no extra overhead.

2 You can save yourself some typing by importing IPython within your .pdbrc file:

try:
    from IPython import embed
except:
    pass

This allows you to simply call embed() from within ipdb (of course, only when IPython is installed).


回答 8

一种选择是使用像Spyder这样的IDE ,它应该允许您在调试时与代码进行交互(实际上是使用IPython控制台)。实际上,Spyder非常类似于MATLAB,我认为这是故意的。其中包括变量检查器,变量编辑,对文档的内置访问等。

One option is to use an IDE like Spyder which should allow you to interact with your code while debugging (using an IPython console, in fact). In fact, Spyder is very MATLAB-like, which I presume was intentional. That includes variable inspectors, variable editing, built-in access to documentation, etc.


回答 9

该问题的正确,简单,酷爽的准确答案是将%run宏与-d标志一起使用。

In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.        
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
      2                                                            
      3                        
----> 4 a=1                                            
      5 b=2

the right, easy, cool, exact answer for the question is to use %run macro with -d flag.

In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.        
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
      2                                                            
      3                        
----> 4 a=1                                            
      5 b=2

回答 10

如果在embed()控制台中键入exit(),代码将继续并转到下一个embed()行。

If you type exit() in embed() console the code continue and go to the next embed() line.


回答 11

Pyzo IDE具有与OP问类似的功能。您不必以调试模式启动。与MATLAB相似,命令在shell中执行。在某些源代码行中设置断点时,IDE会在此处停止执行,并且您还可以调试和发出常规IPython命令。

但是,除非您设置了另一个断点,否则似乎单步执行(还好吗?)效果不佳(即在一行中停下来,然后步入另一功能)。

仍然来自MATLAB,这似乎是我找到的最佳解决方案。

The Pyzo IDE has similar capabilities as the OP asked for. You don’t have to start in debug mode. Similarly to MATLAB, the commands are executed in the shell. When you set up a break-point in some source code line, the IDE stops the execution there and you can debug and issue regular IPython commands as well.

It does seem however that step-into doesn’t (yet?) work well (i.e. stopping in one line and then stepping into another function) unless you set up another break-point.

Still, coming from MATLAB, this seems the best solution I’ve found.


回答 12

在python 3.2中,您具有interact命令,该命令可让您访问完整的python / ipython命令空间。

From python 3.2, you have the interact command, which gives you access to the full python/ipython command space.


回答 13

从Emacs的IPython-shell和通过pdb.set_trace()设置的断点运行应该可以。

与python-mode.el,Mx ipython RET等一起检查

Running from inside Emacs’ IPython-shell and breakpoint set via pdb.set_trace() should work.

Checked with python-mode.el, M-x ipython RET etc.


回答 14

开发新代码

在IPython中进行调试

  1. 使用Jupyter / IPython单元执行来加速实验迭代
  2. 使用%% debug逐步

单元格示例:

%%debug
...: for n in range(4):
...:    n>2

调试现有代码

IPython内部调试

  1. 调试损坏的单元测试: pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb
  2. 调试测试箱子外面:breakpoint()python -m ipdb,等。
  3. IPython.embed()用于在调试器中需要时具有完整的IPython功能

关于Python的想法

我同意OP的观点,MATLAB可以很好地完成许多事情,Python仍然没有,而且确实应该这样做,因为该语言中的几乎所有内容都偏重于开发速度而不是生产速度。也许有一天,我将为CPython贡献一些琐碎的错误修复。

https://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68

另请参见是否可以通过调试在IPython中运行命令?

Developing New Code

Debugging inside IPython

  1. Use Jupyter/IPython cell execution to speed up experiment iterations
  2. Use %%debug for step through

Cell Example:

%%debug
...: for n in range(4):
...:    n>2

Debugging Existing Code

IPython inside debugging

  1. Debugging a broken unit test: pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb
  2. Debugging outside of test case: breakpoint(), python -m ipdb, etc.
  3. IPython.embed() for full IPython functionality where needed while in the debugger

Thoughts on Python

I agree with the OP that many things MATLAB does nicely Python still does not have and really should since just about everything in the language favors development speed over production speed. Maybe someday I will contribute more than trivial bug fixes to CPython.

https://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68

See also Is it possible to run commands in IPython with debugging?


iPython Notebook清除代码中的单元格输出

问题:iPython Notebook清除代码中的单元格输出

在iPython笔记本中,我有一个while循环,可print实时侦听串行端口和接收到的数据。

我想要实现的仅显示最新接收到的数据(即,仅一行显示最新数据。在单元格输出区域中不滚动)

我需要的是(我认为)当我收到新数据时清除旧的单元格输出,然后打印新数据。我想知道如何以编程方式清除旧数据?

In a iPython notebook, I have a while loop that listens to a Serial port and print the received data in real time.

What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area)

What I need(i think) is to clear the old cell output when I receives new data, and then prints the new data. I am wondering how can I clear old data programmatically ?


回答 0

您可以IPython.display.clear_output用来清除单元格的输出。

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

在此循环结束时,您只会看到一个Hello World!

没有代码示例,给您工作代码并不容易。最好缓冲最近的n个事件是一个好策略。每当缓冲区更改时,您都可以清除单元格的输出并再次打印缓冲区。

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it’s not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell’s output and print the buffer again.


回答 1

如果您像我一样来到这里,希望使用Jupitter在Jupyter的Julia笔记本中对地块做同样的事情,则可以使用:

    IJulia.clear_output(true)

所以对于多次运行的动画情节

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

没有clear_output调用,所有图将单独显示。

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.


回答 2

您可以使用IPython.display.clear_output清除输出,如cel的答案所述。我要补充一点,对我而言,最好的解决方案是使用以下参数组合进行打印,而不会出现笔记本的“晃动”:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

You can use the IPython.display.clear_output to clear the output as mentioned in cel’s answer. I would add that for me the best solution was to use this combination of parameters to print without any “shakiness” of the notebook:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

在ipython中运行python脚本

问题:在ipython中运行python脚本

是否可以从ipython内部运行python脚本(而不是模块)而不指示其路径?我尝试设置PYTHONPATH,但它似乎仅适用于模块。我想执行

%run my_script.py

而不在包含文件的目录中。

Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute

%run my_script.py

without being in the directory containing the file.


回答 0

从“ my_script.py”目录中,您可以简单地执行以下操作:

%run ./my_script.py

from within the directory of “my_script.py” you can simply do:

%run ./my_script.py

回答 1

如何在Ipython中运行脚本

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

那应该做

How to run a script in Ipython

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

That should do it


回答 2

%run魔术有一个参数file_finder,它使用来获取完整路径文件来执行(见这里); 如您所述,它只是在当前目录中查找,如有必要,附加“ .py”。

似乎没有要到指定的文件取景器使用方式,从%run魔术,但没有什么可以从定义自己的魔法命令阻止你在调用%run用适当的文件查找。

作为一个非常讨厌的黑客,您可以file_finder使用自己的默认设置覆盖默认设置:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

坦白地说,按照IPython API的变化速度,它与定义您自己的魔术一样可能继续起作用。

The %run magic has a parameter file_finder that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending “.py” if necessary.

There doesn’t seem to be a way to specify which file finder to use from the %run magic, but there’s nothing to stop you from defining your own magic command that calls into %run with an appropriate file finder.

As a very nasty hack, you could override the default file_finder with your own:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

To be honest, at the rate the IPython API is changing that’s as likely to continue to work as defining your own magic is.


回答 3

在python中,模块和脚本之间没有区别;您可以同时执行脚本和模块。该文件必须位于pythonpath AFAIK上,因为python必须能够找到有问题的文件。如果从目录执行python,则该目录会自动添加到pythonpath中。

请参阅什么是从另一个Python脚本调用Python脚本的最佳方法?有关模块和脚本的更多信息

还有一个内置函数execfile(filename)将执行您想要的操作

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want


回答 4

适用于Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

for Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

在iPython Notebook中进行调试的正确方法是什么?

问题:在iPython Notebook中进行调试的正确方法是什么?

我所知, %debug magic可以在一个单元内进行调试。

但是,我有跨多个单元格的函数调用。

例如,

In[1]: def fun1(a)
           def fun2(b)
               # I want to set a breakpoint for the following line #
               return do_some_thing_about(b)

       return fun2(a)

In[2]: import multiprocessing as mp
       pool=mp.Pool(processes=2)
       results=pool.map(fun1, 1.0)
       pool.close()
       pool.join

我试过的

  1. 我试图%debug在cell-1的第一行中设置。但是它甚至在执行单元2之前就立即进入调试模式。

  2. 我试图%debug在代码之前添加该行return do_some_thing_about(b)。但是,代码将永远运行,永远不会停止。

在ipython笔记本中设置断点的正确方法是什么?

As I know, %debug magic can do debug within one cell.

However, I have function calls across multiple cells.

For example,

In[1]: def fun1(a)
           def fun2(b)
               # I want to set a breakpoint for the following line #
               return do_some_thing_about(b)

       return fun2(a)

In[2]: import multiprocessing as mp
       pool=mp.Pool(processes=2)
       results=pool.map(fun1, 1.0)
       pool.close()
       pool.join

What I tried:

  1. I tried to set %debug in the first line of cell-1. But it enter into debug mode immediately, even before executing cell-2.

  2. I tried to add %debug in the line right before the code return do_some_thing_about(b). But then the code runs forever, never stops.

What is the right way to set a break point within the ipython notebook?


回答 0

使用ipdb

通过安装

pip install ipdb

用法:

In[1]: def fun1(a):
   def fun2(a):
       import ipdb; ipdb.set_trace() # debugging starts here
       return do_some_thing_about(b)
   return fun2(a)
In[2]: fun1(1)

用于逐行执行n和进入功能使用,s并退出调试提示使用c

有关可用命令的完整列表:https : //appletree.or.kr/quick_reference_cards/Python/Python%20Debugger%20Cheatsheet.pdf

Use ipdb

Install it via

pip install ipdb

Usage:

In[1]: def fun1(a):
   def fun2(a):
       import ipdb; ipdb.set_trace() # debugging starts here
       return do_some_thing_about(b)
   return fun2(a)
In[2]: fun1(1)

For executing line by line use n and for step into a function use s and to exit from debugging prompt use c.

For complete list of available commands: https://appletree.or.kr/quick_reference_cards/Python/Python%20Debugger%20Cheatsheet.pdf


回答 1

您可以ipdb在jupyter内部使用以下命令:

from IPython.core.debugger import Tracer; Tracer()()

编辑:自IPython 5.1起,不推荐使用上述功能。这是新方法:

from IPython.core.debugger import set_trace

set_trace()在需要断点的地方添加。键入help用于ipdb命令输入字段出现时。

You can use ipdb inside jupyter with:

from IPython.core.debugger import Tracer; Tracer()()

Edit: the functions above are deprecated since IPython 5.1. This is the new approach:

from IPython.core.debugger import set_trace

Add set_trace() where you need a breakpoint. Type help for ipdb commands when the input field appears.


回答 2

您的返回函数位于def函数(主函数)的行中,您必须给它一个制表符。和使用

%%debug 

代替

%debug 

调试整个单元而不仅仅是行。希望这可能对您有帮助。

Your return function is in line of def function(main function), you must give one tab to it. And Use

%%debug 

instead of

%debug 

to debug the whole cell not only line. Hope, maybe this will help you.


回答 3

您始终可以在任何单元格中添加它:

import pdb; pdb.set_trace()

调试器将在该行停止。例如:

In[1]: def fun1(a):
           def fun2(a):
               import pdb; pdb.set_trace() # debugging starts here
           return fun2(a)

In[2]: fun1(1)

You can always add this in any cell:

import pdb; pdb.set_trace()

and the debugger will stop on that line. For example:

In[1]: def fun1(a):
           def fun2(a):
               import pdb; pdb.set_trace() # debugging starts here
           return fun2(a)

In[2]: fun1(1)

回答 4

在Python 3.7中,您可以使用breakpoint()函数。只需输入

breakpoint()

无论您想在哪里停止运行时,都可以使用相同的pdb命令(r,c,n,…)或评估变量。

In Python 3.7 you can use breakpoint() function. Just enter

breakpoint()

wherever you would like runtime to stop and from there you can use the same pdb commands (r, c, n, …) or evaluate your variables.


回答 5

只需键入import pdb在jupyter笔记本,然后用这个的cheatsheet调试。非常方便

c->继续,s->步进,b 12->在第12行设置断点,依此类推。

一些有用的链接: pdb上的Python官方文档Python pdb调试器示例,以更好地了解如何使用调试器命令

一些有用的屏幕截图:

Just type import pdb in jupyter notebook, and then use this cheatsheet to debug. It’s very convenient.

c –> continue, s –> step, b 12 –> set break point at line 12 and so on.

Some useful links: Python Official Document on pdb, Python pdb debugger examples for better understanding how to use the debugger commands.

Some useful screenshots:


回答 6

得到错误后,在下一个单元格中运行%debug,仅此而已。

After you get an error, in the next cell just run %debug and that’s it.


回答 7

%pdb魔术的命令是很好用为好。只需说一遍%pdb on,随后pdb调试器将在所有异常上运行,无论调用堆栈中有多深。非常便利。

如果您有要调试的特定行,只需在此处引发一个异常(通常您已经!),或使用%debug其他人一直在建议的magic命令。

The %pdb magic command is good to use as well. Just say %pdb on and subsequently the pdb debugger will run on all exceptions, no matter how deep in the call stack. Very handy.

If you have a particular line that you want to debug, just raise an exception there (often you already are!) or use the %debug magic command that other folks have been suggesting.


回答 8

我刚刚发现了PixieDebugger。甚至以为我还没有时间进行测试,这似乎确实是调试我们在ipdb中使用ipython的方式的最相似方法

它还有一个“评估”标签

I just discovered PixieDebugger. Even thought I have not yet had the time to test it, it really seems the most similar way to debug the way we’re used in ipython with ipdb

It also has an “evaluate” tab


回答 9

提供了本机调试器作为JupyterLab的扩展。可以在几周前发布,可以通过获取相关扩展以及xeus-python内核(尤其是没有ipykernel用户众所周知的魔术)来安装它:

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

这样可以实现其他IDE众所周知的可视化调试体验。

来源:Jupyter的可视调试器

A native debugger is being made available as an extension to JupyterLab. Released a few weeks ago, this can be installed by getting the relevant extension, as well as xeus-python kernel (which notably comes without the magics well-known to ipykernel users):

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

This enables a visual debugging experience well-known from other IDEs.

Source: A visual debugger for Jupyter


输入python或ipython解释器时自动导入模块

问题:输入python或ipython解释器时自动导入模块

我发现自己import numpy as np几乎每次启动python解释器时都要输入。如何设置python或ipython解释器,以便自动导入numpy?

I find myself typing import numpy as np almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported?


回答 0

使用环境变量PYTHONSTARTUP。根据官方文档:

如果这是可读文件的名称,则在以交互方式显示第一个提示之前,将执行该文件中的Python命令。在与执行交互命令相同的命名空间中执行文件,以便在其中定义或导入的对象可以在交互会话中使用而无需限定。

因此,只需使用import语句创建一个python脚本,然后将环境变量指向该脚本即可。话虽如此,请记住,“显式总是比隐式更好”,因此不要在生产脚本中依赖此行为。

对于Ipython,请参阅教程,了解如何制作ipython_config文件

Use the environment variable PYTHONSTARTUP. From the official documentation:

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session.

So, just create a python script with the import statement and point the environment variable to it. Having said that, remember that ‘Explicit is always better than implicit’, so don’t rely on this behavior for production scripts.

For Ipython, see this tutorial on how to make a ipython_config file


回答 1

对于ipython,有两种方法可以实现此目的。两者都涉及位于的ipython的配置目录~/.ipython

  1. 创建一个自定义的ipython配置文件。
  2. 或者您可以将启动文件添加到 ~/.ipython/profile_default/startup/

为简单起见,我将使用选项2。您所要做的就是在目录中放置一个.py.ipy文件,~/.ipython/profile_default/startup它将自动执行。因此,您可以将其放置import numpy as np在简单文件中,然后在ipython提示符的命名空间中使用np。

选项2实际上将与自定义配置文件一起使用,但是使用自定义配置文件将使您可以根据特定情况更改启动要求和其他配置。但是,如果您始终希望np有空,请务必将其放在启动目录中。

有关ipython配置的更多信息。该文档有一个更完整的解释。

For ipython, there are two ways to achieve this. Both involve ipython’s configuration directory which is located in ~/.ipython.

  1. Create a custom ipython profile.
  2. Or you can add a startup file to ~/.ipython/profile_default/startup/

For simplicity, I’d use option 2. All you have to do is place a .py or .ipy file in the ~/.ipython/profile_default/startup directory and it will automatically be executed. So you could simple place import numpy as np in a simple file and you’ll have np in the namespace of your ipython prompt.

Option 2 will actually work with a custom profile, but using a custom profile will allow you to change the startup requirements and other configuration based on a particular case. However, if you’d always like np to be available to you then by all means put it in the startup directory.

For more information on ipython configuration. The docs have a much more complete explanation.


回答 2

我使用〜/ .startup.py文件,如下所示:

# Ned's .startup.py file
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")

pp = pprint.pprint

然后定义PYTHONSTARTUP =〜/ .startup.py,Python将在启动shell时使用它。

打印语句在那里,因此当我启动外壳程序时,会提醒我它已经生效,并且已经导入了什么内容。该pp快捷方式实在是太好用太…

I use a ~/.startup.py file like this:

# Ned's .startup.py file
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")

pp = pprint.pprint

Then define PYTHONSTARTUP=~/.startup.py, and Python will use it when starting a shell.

The print statements are there so when I start the shell, I get a reminder that it’s in effect, and what has been imported already. The pp shortcut is really handy too…


回答 3

虽然在大多数情况下创建诸如ravenac95 建议之类的自定义启动脚本是最佳的通用答案,但在要使用的情况下它将无法正常工作from __future__ import X。如果您有时在Python 2.x中工作,但想使用现代除法,则只有一种方法可以做到这一点。创建配置文件后,编辑profile_default(对于Ubuntu,位于~/.ipython/profile_default),然后在底部添加以下内容:

c.InteractiveShellApp.exec_lines = [
    'from __future__ import division, print_function',
    'import numpy as np',
    'import matplotlib.pyplot as plt',
    ]

While creating a custom startup script like ravenac95 suggests is the best general answer for most cases, it won’t work in circumstances where you want to use a from __future__ import X. If you sometimes work in Python 2.x but want to use modern division, there is only one way to do this. Once you create a profile, edit the profile_default (For Ubuntu this is located in ~/.ipython/profile_default) and add something like the following to the bottom:

c.InteractiveShellApp.exec_lines = [
    'from __future__ import division, print_function',
    'import numpy as np',
    'import matplotlib.pyplot as plt',
    ]

回答 4

在Linux上,作为可接受答案的更简单替代方法:

只需定义一个别名即可,例如放入alias pynp='python -i -c"import numpy as np"'您的〜/ .bash_aliases文件中。然后pynp,您可以使用调用python + numpy ,并且仍然可以仅使用python python。Python脚本的行为保持不变。

As a simpler alternative to the accepted answer, on linux:

just define an alias, e.g. put alias pynp='python -i -c"import numpy as np"' in your ~/.bash_aliases file. You can then invoke python+numpy with pynp, and you can still use just python with python. Python scripts’ behaviour is left untouched.


回答 5

您可以创建普通的python脚本,也可以根据需要创建import_numpy.py任何脚本

#!/bin/env python3
import numpy as np

然后用-i标志启动它。

python -i import_numpy.py

这样,您便可以灵活地只为不同的项目选择所需的模块。

You can create a normal python script as import_numpy.py or anything you like

#!/bin/env python3
import numpy as np

then launch it with -i flag.

python -i import_numpy.py

Way like this will give you flexibility to choose only modules you want for different projects.


回答 6

正如ravenac95在他的回答中提到的那样,您可以创建自定义配置文件或修改默认配置文件。此答案是import numpy as np自动需要的Linux命令的快速视图。

如果要使用名为的定制概要文件numpy,请运行:

ipython profile create numpy
echo 'import numpy as np' >> $(ipython locate profile numpy)/startup/00_imports.py
ipython --profile=numpy

或者,如果您想修改默认配置文件以始终导入numpy:

echo 'import numpy as np' >> $(ipython locate profile default)/startup/00_imports.py
ipython

查看IPython配置教程,以深入了解配置文件。请参阅.ipython/profile_default/startup/README以了解启动目录的工作方式。

As ravenac95 mentioned in his answer, you can either create a custom profile or modify the default profile. This answer is quick view of Linux commands needed to import numpy as np automatically.

If you want to use a custom profile called numpy, run:

ipython profile create numpy
echo 'import numpy as np' >> $(ipython locate profile numpy)/startup/00_imports.py
ipython --profile=numpy

Or if you want to modify the default profile to always import numpy:

echo 'import numpy as np' >> $(ipython locate profile default)/startup/00_imports.py
ipython

Check out the IPython config tutorial to read more in depth about configuring profiles. See .ipython/profile_default/startup/README to understand how the startup directory works.


回答 7

我的默认ipython调用是

ipython --pylab --nosep --InteractiveShellApp.pylab_import_all=False

--pylab已经有ipython一段时间了。它导入numpy和(的一部分)matplotlib。我添加了该--Inter...选项,因此它不使用*导入,因为我更喜欢使用explicit np....

这可以是快捷方式,别名或脚本。

My default ipython invocation is

ipython --pylab --nosep --InteractiveShellApp.pylab_import_all=False

--pylab has been a ipython option for some time. It imports numpy and (parts of) matplotlib. I’ve added the --Inter... option so it does not use the * import, since I prefer to use the explicit np.....

This can be a shortcut, alias or script.


如何在Jupyter中显示完整输出,而不仅仅是最后结果?

问题:如何在Jupyter中显示完整输出,而不仅仅是最后结果?

我希望Jupyter打印所有交互式输出,而不要打印,而不仅仅是最后的结果。怎么做?

范例:

a=3
a
a+1

我想展示

3
4

I want Jupyter to print all the interactive output without resorting to print, not only the last result. How to do it?

Example :

a=3
a
a+1

I would like to display

3
4


回答 0

感谢Thomas,这是我一直在寻找的解决方案:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Thanks to Thomas, here is the solution I was looking for:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

回答 1

https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/

1)将此代码放在Jupyter单元格中:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

2)在Windows中,以下步骤使更改永久生效。应该适用于其他操作系统。您可能必须更改路径。

C:\Users\your_profile\\.ipython\profile_default

使用以下代码在profile_defaults中创建一个ipython_config.py文件:

c = get_config()

c.InteractiveShell.ast_node_interactivity = "all"

https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/

1) Place this code in a Jupyter cell:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

2) In Windows, the steps below makes the change permanent. Should work for other operating systems. You might have to change the path.

C:\Users\your_profile\\.ipython\profile_default

Make a ipython_config.py file in the profile_defaults with the following code:

c = get_config()

c.InteractiveShell.ast_node_interactivity = "all"

回答 2

每个笔记本的基础

正如其他人回答的那样,将以下代码放入Jupyter Lab或Jupyter Notebook单元将起作用:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

永久改变

但是,如果您想永久保留它并使用Jupyter Lab,则需要创建一个IPython Notebook配置文件。运行以下命令来执行此操作(如果您使用Jupyter Notebook,则不要运行-以下是更多详细信息):

ipython profile create

如果您使用的是Jupyter Notebook,则应该已经创建了此文件,因此无需再次运行它。实际上,运行此命令可能会覆盖您当前的首选项。

创建此文件后,对于Jupyter Lab和Notebook用户一样,将以下代码添加到该文件中C:\Users\USERNAME\\.ipython\profile_default\ipython_config.py

c.InteractiveShell.ast_node_interactivity = "all"

我发现c = get_config()在新版本的Jupyter中没有必要 ,但是如果这对您不起作用,请c = get_config()在文件的开头添加。

有关以外的其他标志选项"all",请访问以下链接:https : //ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-InteractiveShell.ast_node_interactivity

Per Notebook Basis

As others have answered, putting the following code in a Jupyter Lab or Jupyter Notebook cell will work:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

Permanent Change

However, if you would like to make this permanent and use Jupyter Lab, you will need to create an IPython notebook config file. Run the following command to do so (DO NOT run if you use Jupyter Notebook – more details below):

ipython profile create

If you are using Jupyter Notebook, this file should have already been created and there will be no need to run it again. In fact, running this command may overwrite your current preferences.

Once you have this file created, for Jupyter Lab and Notebook users alike, add the following code to the file C:\Users\USERNAME\\.ipython\profile_default\ipython_config.py:

c.InteractiveShell.ast_node_interactivity = "all"

I found there is no need for c = get_config() in the newer versions of Jupyter, but if this doesn’t work for you, add the c = get_config() to the beginning of the file.

For more flag options other than "all", visit this link: https://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-InteractiveShell.ast_node_interactivity


python中的%timeit是什么?

问题:python中的%timeit是什么?

我总是像这样阅读代码来计算时间:

%timeit function()

您能在这里解释什么是“%”吗?

我认为,“%”总是用于替换字符串中的某些内容,例如%s表示替换字符串,%d替换数据,但是我不知道这种情况。

I always read the code to calculate the time like this way:

%timeit function()

Can you explain what means “%” here?

I think, the “%” is always used to replace something in a string, like %s means replace a string, %d replace a data, but I have no idea about this case.


回答 0

%timeitipython的魔术函数,可用于计时特定代码段(单个执行语句或单个方法)。

从文档:

%timeit

Time execution of a Python statement or expression

Usage, in line mode:
    %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement

要使用它,例如,如果我们想确定using是否xrange比using更快range,则只需执行以下操作:

In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop

In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 µs per loop

您将获得他们的时间安排。

主要优点%timeit是:

  • 不必timeit.timeit 从标准库中导入代码,也可以多次运行代码以找出哪种方法更好。

  • %timeit将基于总共2秒的执行窗口自动计算代码所需的运行次数。

  • 您还可以使用当前的控制台变量,而无需传递整个代码片段,以防timeit.timeit构建在另一个可以正常工作的环境中构建的变量。

%timeit is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method).

From the docs:

%timeit

Time execution of a Python statement or expression

Usage, in line mode:
    %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement

To use it, for example if we want to find out whether using xrange is any faster than using range, you can simply do:

In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop

In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 µs per loop

And you will get the timings for them.

The major advantage of %timeit are:

  • that you don’t have to import timeit.timeit from the standard library, and run the code multiple times to figure out which is the better approach.

  • %timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.

  • You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit to built the variable that is built in an another environment that timeit works.


回答 1

这就是所谓的一系魔法中的IPython。它们的独特之处在于其参数仅扩展到当前行的末尾,而魔术本身的确是为命令行开发而构造的。 timeit用于定时执行代码。

如果您想查看所有可以使用的魔法,只需键入:

%lsmagic

以获得线魔术和细胞魔术的列表。

从文档的某些其它神奇信息在这里

IPython具有一个称为魔术的命令系统,该系统有效地提供了一种迷你命令语言,该语言与Python的语法正交,并且可由用户使用新命令进行扩展。魔术应该以交互方式键入,因此它们使用命令行约定,例如使用空格分隔参数,使用破折号表示选项以及命令行环境中的其他典型约定。

根据您是处于模式还是单元格模式,有两种不同的使用方法%timeit。您的问题说明了第一种方式:

In [1]: %timeit range(100)

In [1]: %%timeit 
      : x = range(100)
      :

This is known as a line magic in iPython. They are unique in that their arguments only extend to the end of the current line, and magics themselves are really structured for command line development. timeit is used to time the execution of code.

If you wanted to see all of the magics you can use, you could simply type:

%lsmagic

to get a list of both line magics and cell magics.

Some further magic information from documentation here:

IPython has a system of commands we call magics that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.

Depending on whether you are in line or cell mode, there are two different ways to use %timeit. Your question illustrates the first way:

In [1]: %timeit range(100)

vs.

In [1]: %%timeit 
      : x = range(100)
      :

回答 2

IPython拦截了这些命令,它们被称为内置魔术命令,这是列表:https : //ipython.org/ipython-doc/dev/interactive/magics.html

您还可以创建自己的自定义魔术,https: //ipython.org/ipython-doc/dev/config/custommagics.html

timeit在这里https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit

IPython intercepts those, they’re called built-in magic commands, here’s the list: https://ipython.org/ipython-doc/dev/interactive/magics.html

You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html

Your timeit is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit


回答 3

我只想添加另一个有用的优点,即使用%timeit通过mu无应答

  • 也可以使用当前的控制台变量,而无需像timeit.timeit那样传递整个代码片段,以构建在timeit可以工作的另一个环境中构建的变量。

PS:我知道这应该是上面回答的评论,但是我目前对此没有足够的声誉,希望我写的内容对某人有帮助,并帮助我赢得足够的声誉,以便下次发表评论。

I would just like to add another useful advantage of using %timeit to answer by mu 無 that:

  • You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit to built the variable that is built in an another enviroment that timeit works.

PS: I know this should be a comment to answer above but I currently don’t have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.


回答 4

我只是想添加一个关于%% timeit的非常微妙的观点。如果它在单元上运行“魔术” ,您将得到错误…

UsageError:%%timeit找不到行魔术函数

…如果%% timeit上方有任何代码/注释行。换句话说,请确保%% timeit是单元格中的第一个命令。

我知道这是所有专家都不会说的一个小问题,但是我只是想为年轻的巫师们以魔术开始增加我的半分钱。

I just wanted to add a very subtle point about %%timeit. Given it runs the “magics” on the cell, you’ll get error…

UsageError: Line magic function %%timeit not found

…if there is any code/comment lines above %%timeit. In other words, ensure that %%timeit is the first command in your cell.

I know it’s a small point all the experts will say duh to, but just wanted to add my half a cent for the young wizards starting out with magic tricks.


回答 5

行魔法前缀与的性格和工作很像OS命令行调用:他们得到作为参数的行,其中参数都没有括号或引号传递的其余部分。单元魔术%%作为双前缀,并且它们是函数,它们不仅作为该行的其余部分作为参数,而且还作为单独的参数作为其下方的行的参数。

Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.


如何在* nix下的ipython中使用vi键?

问题:如何在* nix下的ipython中使用vi键?

当前在Bash中,我用于set -o vi在bash提示符中启用vi模式。

我如何在ipython中进行此操作?

注意:如果答案适用于所有* nix,我将从标题中删除OS X :)

Currently in Bash I use set -o vi to enable vi mode in my bash prompt.

How do I get this going in ipython?

Note: If an answer applies to all *nix, I’ll remove the OS X from the title :)


回答 0

如果有人最近在这里闲逛,那么IPython 5.0从readline切换到hint_toolkit,因此对此问题的更新答案是传递一个选项:

$ ipython --TerminalInteractiveShell.editing_mode=vi

…或在配置文件配置中进行全局设置(~/.ipython/profile_default/ipython_config.pyipython profile create如果没有,则使用创建):

c.TerminalInteractiveShell.editing_mode = 'vi'

In case someone’s wandering in here recently, IPython 5.0 switched from readline to prompt_toolkit, so an updated answer to this question is to pass an option:

$ ipython --TerminalInteractiveShell.editing_mode=vi

… or to set it globally in the profile configuration (~/.ipython/profile_default/ipython_config.py; create it with ipython profile create if you don’t have it) with:

c.TerminalInteractiveShell.editing_mode = 'vi'

回答 1

看来解决方案适用于许多其他与Readline兼容的应用程序:

~/.inputrc文件中设置以下内容:

set editing-mode vi
set keymap vi
set convert-meta on

资料来源:http : //www.jukie.net/bart/blog/20040326082602

Looks like a solution works for many other readline compatible apps:

Set the following in your ~/.inputrc file:

set editing-mode vi
set keymap vi
set convert-meta on

Source: http://www.jukie.net/bart/blog/20040326082602


回答 2

您也可以在Vi-mode和Emacs模式之间交互切换。根据readline文档在它们之间进行切换,您应该能够使用MCj组合键,但这似乎只允许我切换到vi模式-在Mac上(其中ESC被用作“ Meta”键) )是:ESC+ CTRL+ j。要切换回Emacs模式,可以使用Ce,但对我而言似乎不起作用-我不得不改用MCe-在Mac上是:ESC+ CTRL+ e

仅供参考我的〜/ .inputrc设置如下:

set meta-flag on
set input-meta on
set convert-meta off
set output-meta on

You can also interactively switch between Vi-mode and Emacs mode. According to the the readline docs to switch between them you are supposed to be able to use the M-C-j key combination but that only seems to allow me to switch to vi-mode – on my Mac (where ESC is used as the ‘Meta’ key) it is: ESC+CTRL+j. To switch back to Emacs mode one can use C-e but that didn’t appear to work for me – I had to instead do M-C-e – on my Mac it is: ESC+CTRL+e.

FYI my ~/.inputrc is set up as follows:

set meta-flag on
set input-meta on
set convert-meta off
set output-meta on

回答 3

ipython使用readline库,并且可以使用该~/.inputrc文件进行配置。你可以加

set editing-mode vi

到该文件,以使所有readline基础应用程序都使用vi样式键绑定而不是Emacs。

ipython uses the readline library and this is configurable using the ~/.inputrc file. You can add

set editing-mode vi

to that file to make all readline based applications use vi style keybindings instead of Emacs.


回答 4

我需要能够在IPython 5中交互地切换模式,我发现可以通过即时创建提示管理器来做到这一点:

a = get_ipython().configurables[0]; a.editing_mode='vi'; a.init_prompt_toolkit_cli()

I needed to be able to switch modes interactively in IPython 5 and I found you can do so by recreating the prompt manager on the fly:

a = get_ipython().configurables[0]; a.editing_mode='vi'; a.init_prompt_toolkit_cli()

回答 5

您可以在.ipython启动配置文件中设置vi。如果没有,则创建一个文件,方法是添加一个~/.ipython/profile_default/startup/名为的文件start.py。这是一个例子:

# Initializing script for ipython in ~/.ipython/profile_default/startup/
from IPython import get_ipython
ipython = get_ipython()

# If in ipython, set vi and load autoreload extension
if 'ipython' in globals():
    ipython.editing_mode = 'vi'
    ipython.magic('load_ext autoreload')
    ipython.magic('autoreload 2')
from Myapp.models import * 

最后一行是如果您将ipython与Django一起使用,并且要默认导入所有模型。

You may set vi in your .ipython start-up config file. Create one if you don’t have it by adding a file to ~/.ipython/profile_default/startup/ called something like start.py. Here’s an example:

# Initializing script for ipython in ~/.ipython/profile_default/startup/
from IPython import get_ipython
ipython = get_ipython()

# If in ipython, set vi and load autoreload extension
if 'ipython' in globals():
    ipython.editing_mode = 'vi'
    ipython.magic('load_ext autoreload')
    ipython.magic('autoreload 2')
from Myapp.models import * 

That last line is if you use ipython with Django, and want to import all your models by default.


如何正确关闭IPython Notebook?

问题:如何正确关闭IPython Notebook?

如何正确关闭IPython Notebook?

目前,我只是关闭浏览器选项卡,然后Ctrl+C在终端中使用。
不幸的是,exit()滴答和滴答都Kill kernel upon exit没有帮助(它们确实杀死了它们的内核,但是没有退出iPython)。

How to close IPython Notebook properly?

Currently, I just close the browser tabs and then use Ctrl+C in the terminal.
Unfortunately, neither exit() nor ticking Kill kernel upon exit does help (they do kill the kernel they but don’t exit the iPython).


回答 0

当前没有比终端中的Ctrl + C更好的方法了。

我们正在考虑如何进行显式关机,但是笔记本作为单用户应用程序(用户可以自由停止它)和作为多用户服务器(只能由管理员使用)之间存在一定的压力。阻止它。我们还没有弄清楚如何处理差异。

(对于将来的读者来说,就是0.12已发布而0.13正在开发中的情况。)

2017年12月更新

IPython Notebook已成为Jupyter Notebook。最新版本添加了jupyter notebook stopshell命令,该命令将关闭在该系统上运行的服务器。如果不是默认端口8888,则可以在命令行中传递端口号。

您还可以使用nbmanager,它是一个桌面应用程序,可以显示正在运行的服务器并关闭它们。

最后,我们正在努力添加:

  • 一个配置选项,如果您在指定时间内不使用服务器,则会自动关闭服务器。
  • 用户界面中的一个按钮,用于关闭服务器。(我们知道花了这么长时间真是太疯狂了。更改UI引发了争议。)

There isn’t currently a better way to do it than Ctrl+C in the terminal.

We’re thinking about how to have an explicit shutdown, but there’s some tension between the notebook as a single-user application, where the user is free to stop it, and as a multi-user server, where only an admin should be able to stop it. We haven’t quite worked out how to handle the differences yet.

(For future readers, this is the situation with 0.12 released and 0.13 in development.)

Update December 2017

The IPython Notebook has become the Jupyter Notebook. A recent version has added a jupyter notebook stop shell command which will shut down a server running on that system. You can pass the port number at the command line if it’s not the default port 8888.

You can also use nbmanager, a desktop application which can show running servers and shut them down.

Finally, we are working on adding:

  • A config option to automatically shut down the server if you don’t use it for a specified time.
  • A button in the user interface to shut the server down. (We know it’s a bit crazy that it has taken this long. Changing UI is controversial.)

回答 1

如果您像我一样在后台运行jupyter:

jupyter notebook &> /dev/null &

然后要完全退出jupyter,而不是Ctl-C,请使用别名命令:

echo 'alias quitjupyter="kill $(pgrep jupyter)"' >> ~/.bashrc

重新启动终端。杀死所有jupyter实例:

quitjupyter

注意:如上所示,在单引号内使用双引号。另一种方法是在将表达式写入您的.bashrc之前先对表达式求值(您要编写的命令本身不是’kill 1430’或可能与当前jupyter实例相关的任何进程号)。当然,您可以使用任何所需的别名。我实际上使用’qjup’:

echo 'alias qjup="kill $(pgrep jupyter)"' >> ~/.bashrc

重新启动终端。杀死所有jupyter实例:

qjup

If you run jupyter in the background like me:

jupyter notebook &> /dev/null &

Then to exit jupyter completely, instead of Ctl-C, make an alias command:

echo 'alias quitjupyter="kill $(pgrep jupyter)"' >> ~/.bashrc

Restart your terminal. Kill all jupyter instances:

quitjupyter

Note: use double quotes inside of single quotes as shown above. The other way around will evaluate the expression before writing it to your .bashrc (you want to write the command itself not ‘kill 1430’ or whatever process number may be associated with a current jupyter instance). Of course you can use any alias you wish. I actually use ‘qjup’:

echo 'alias qjup="kill $(pgrep jupyter)"' >> ~/.bashrc

Restart your terminal. Kill all jupyter instances:

qjup

回答 2

我认为已接受的答案已过时,不再有效。

您可以从文件菜单项上的Web界面终止Jupyter Notebook。

将鼠标光标移至“关闭并停止”位置时,将看到以下说明。

当您单击“关闭并停止”时,您将在终端屏幕上看到以下消息。

I think accepted answer outdated and is not valid anymore.

You can terminate jupyter notebook from web interface on file menü item.

When you move Mouse cursor on “close and halt”, you will see following explanation.

And when you click “close and halt”, you will see following message on terminal screen.


回答 3

第一步是保存所有打开的笔记本。然后考虑关闭正在运行的Jupyter Notebook。您可以使用以下简单命令:

$ jupyter notebook stop 
Shutting down server on port 8888 ...

它也将端口号作为参数,您可以正常关闭jupyter笔记本。

例如:

jupyter notebook stop 8889 
Shutting down server on port 8889 ...

此外,要了解您当前的juypter实例正在运行,请检查以下命令:

shell> juypter notebook list 
Currently running servers:
http://localhost:8888/?token=ef12021898c435f865ec706d7c9af8607a7ba58bbee98632 :: /Users/username/jupyter-notebooks [/code]

First step is to save all open notebooks. And then think about shutting down your running Jupyter Notebook. You can use this simple command:

$ jupyter notebook stop 
Shutting down server on port 8888 ...

Which also takes the port number as argument and you can shut down the jupyter notebook gracefully.

For eg:

jupyter notebook stop 8889 
Shutting down server on port 8889 ...

Additionally to know your current juypter instance running, check below command:

shell> juypter notebook list 
Currently running servers:
http://localhost:8888/?token=ef12021898c435f865ec706d7c9af8607a7ba58bbee98632 :: /Users/username/jupyter-notebooks [/code]

回答 4

这些命令对我有用:

jupyter notebook list # shows the running notebooks and their port-numbers
                      # (for instance: 8080)
lsof -n -i4TCP:[port-number] # shows PID.
kill -9 [PID] # kill the process.

这个答案改编自这里

These commands worked for me:

jupyter notebook list # shows the running notebooks and their port-numbers
                      # (for instance: 8080)
lsof -n -i4TCP:[port-number] # shows PID.
kill -9 [PID] # kill the process.

This answer was adapted from here.


回答 5

如果没有其他作用,请尝试从任务管理器(如果是Windows)中终止pythonw进程。

Try killing the pythonw process from the Task Manager (if Windows) if nothing else works.


回答 6

Linux (Ubuntu 14.04)

如前所述,尝试通过先转到ipynb / jupyter浏览器会话中的“运行”选项卡来正确终止ipython Notebook进程,然后检查控制台上打开的终端并使用ctrl-c关闭。如果可能,应避免后者。

如果您运行,ipython notebook list并继续看到在不同端口上运行ipython服务器,请记下现有笔记本计算机将服务于哪些端口。然后关闭您的TCP端口:

fuser -k 'port#'/tcp 

我不确定这样做是否还会涉及其他风险。如果是这样,请告诉我。

Linux (Ubuntu 14.04)

As mentioned, try to kill ipython notebook processes properly by first going to the “running” tab in your ipynb/jupyter browser session, and then check open terminals on your console and shut down with ctrl-c. The latter should be avoided if possible.

If you run an ipython notebook list and continue to see running ipython servers at different ports, make note of which ports the existing notebooks are being served to. Then shut down your TCP ports:

fuser -k 'port#'/tcp 

I’m not sure if there are other risks involved with doing this. If so, let me know.


回答 7

环境


我的操作系统是Ubuntu 16.04,jupyter是4.3.0。

方法


首先,我在浏览器的主页上注销了jupyter(注销按钮在右上角)

第二,输入Ctrl + C您的终端,它显示:

[I 15:59:48.407 NotebookApp]从本地目录中断服务笔记本:/ home / Username 0活动内核

Jupyter Notebook在以下位置运行: http:// localhost:8888 /?token = a572c743dfb73eee28538f9a181bf4d9ad412b19fbb96c82

关闭此笔记本服务器(y / [n])?

最后一步,y在5秒钟内键入,如果显示:

[C 15:59:50.407 NotebookApp]已确认关闭
[I 15:59:50.408 NotebookApp]正在关闭内核

恭喜!您成功关闭了jupyter。

Environment


My OS is Ubuntu 16.04 and jupyter is 4.3.0.

Method


First, i logged out jupyter at its homepage on browser(the logout button is at top-right)

Second, type in Ctrl + C in your terminal and it shows:

[I 15:59:48.407 NotebookApp]interrupted Serving notebooks from local directory: /home/Username 0 active kernels

The Jupyter Notebook is running at: http://localhost:8888/?token=a572c743dfb73eee28538f9a181bf4d9ad412b19fbb96c82

Shutdown this notebook server (y/[n])?

Last step, type in y within 5 sec, and if it shows:

[C 15:59:50.407 NotebookApp] Shutdown confirmed
[I 15:59:50.408 NotebookApp] Shutting down kernels

Congrats! You close your jupyter successfully.


回答 8

实际上,我相信有一种比使用kill或task manager杀死进程更干净的方法。

在Jupyter Notebook仪表板(首次启动“ Jupyter Notebook”时会看到的浏览器界面)中,浏览到浏览器中已关闭但其内核可能仍在运行的笔记本文件的位置。

iPython Notebook文件带有书本图标,如果它具有正在运行的内核,则显示为绿色,如果内核未运行,则显示为灰色。

只需选中正在运行的文件旁边的复选框,然后单击出现在文件上方的“关机”按钮即可。

这将正确关闭与该特定笔记本电脑关联的内核。

Actually, I believe there’s a cleaner way than killing the process(es) using kill or task manager.

In the Jupyter Notebook Dashboard (the browser interface you see when you first launch ‘jupyter notebook’), browse to the location of notebook files you have closed in the browser, but whose kernels may still be running.

iPython Notebook files appear with a book icon, shown in green if it has a running kernel, or gray if the kernel is not running.

Just select the tick box next to the running file, then click on the Shutdown button that appears above it.

This will properly shut down the kernel associated with that specific notebook.


回答 9

在浏览器会话中,您也可以转到Kernel,然后单击Restart and Clear Output

In the browser session you can also go to Kernel and then click Restart and Clear Output.


回答 10

我复制从Jupyter / IPython的笔记本电脑快速入门指南文档粘贴,发布了2月13日,2018年 http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html

1.3.3关闭笔记本:内核关闭打开笔记本时,将自动启动其“计算引擎”(称为内核)。关闭笔记本浏览器选项卡将不会关闭内核,而是内核将一直运行直到被明确关闭。要关闭内核,请转到关联的笔记本,然后单击菜单文件->关闭并暂停。另外,笔记本仪表板有一个名为“运行”的选项卡,其中显示了所有正在运行的笔记本(即内核),并允许将其关闭(通过单击“关机”按钮)。

摘要:首先关闭并停止笔记本计算机的运行。

1.3.2关闭Jupyter Notebook应用程序关闭浏览器(或选项卡)将不会关闭Jupyter Notebook应用程序。要完全关闭它,您需要关闭关联的终端。更详细地说,Jupyter Notebook应用程序是一台服务器,显示在浏览器中的默认地址(http:// localhost:8888)。关闭浏览器不会关闭服务器。您可以重新打开以前的地址,然后Jupyter Notebook应用将重新显示。您可以运行Jupyter Notebook应用程序的许多副本,它们将显示在相似的地址上(只有端口“:”之后的数字才会为每个新副本递增)。由于只有一个Jupyter Notebook App,您已经可以打开许多笔记本,因此我们不建议您运行Jupyter Notebook App的多个副本。

摘要:其次,退出您从其发射Jupyter的终端。

I am copy pasting from the Jupyter/IPython Notebook Quick Start Guide Documentation, released on Feb 13, 2018. http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html

1.3.3 Close a notebook: kernel shut down When a notebook is opened, its “computational engine” (called the kernel) is automatically started. Closing the notebook browser tab, will not shut down the kernel, instead the kernel will keep running until is explicitly shut down. To shut down a kernel, go to the associated notebook and click on menu File -> Close and Halt. Alternatively, the Notebook Dashboard has a tab named Running that shows all the running notebooks (i.e. kernels) and allows shutting them down (by clicking on a Shutdown button).

Summary: First close and halt the notebooks running.

1.3.2 Shut down the Jupyter Notebook App Closing the browser (or the tab) will not close the Jupyter Notebook App. To completely shut it down you need to close the associated terminal. In more detail, the Jupyter Notebook App is a server that appears in your browser at a default address (http://localhost:8888). Closing the browser will not shut down the server. You can reopen the previous address and the Jupyter Notebook App will be redisplayed. You can run many copies of the Jupyter Notebook App and they will show up at a similar address (only the number after “:”, which is the port, will increment for each new copy). Since with a single Jupyter Notebook App you can already open many notebooks, we do not recommend running multiple copies of Jupyter Notebook App.

Summary: Second, quit the terminal from which you fired Jupyter.


回答 11

步骤1-在shell上,只需执行control + z(control + c)步骤2 _关闭Web浏览器

Step 1 – On shell just do control+z (control+c) Step 2 _ close the web browser


如何在ipython笔记本中显示PIL图像

问题:如何在ipython笔记本中显示PIL图像

这是我的代码

from PIL import Image
pil_im = Image.open('data/empire.jpg')

我想对其进行一些图像处理,然后在屏幕上显示它。
我在python笔记本中显示PIL图像时遇到问题。

我努力了:

print pil_im

而只是

pil_im

但是两者都给我:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=569x800 at 0x10ECA0710>

This is my code

from PIL import Image
pil_im = Image.open('data/empire.jpg')

I would like to do some image manipulation on it, and then show it on screen.
I am having problem with showing PIL Image in python notebook.

I have tried:

print pil_im

And just

pil_im

But both just give me:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=569x800 at 0x10ECA0710>

回答 0

您可以使用IPython Module: display加载图像。您可以从Doc阅读更多内容。

from IPython.display import Image 
pil_img = Image(filename='data/empire.jpg')
display(pil_img)

更新

由于OP的要求是使用PIL,如果要显示嵌入式图像,也可以使用matplotlib.pyplot.imshownumpy.asarray例如:

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image

%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))

如果只需要预览而不是内联,则可以这样使用show

pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()

You can use IPython’s Module: display to load the image. You can read more from the Doc.

from IPython.display import Image 
pil_img = Image(filename='data/empire.jpg')
display(pil_img)

updated

As OP’s requirement is to use PIL, if you want to show inline image, you can use matplotlib.pyplot.imshow with numpy.asarray like this too:

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image

%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))

If you only require a preview rather than an inline, you may just use show like this:

pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()

回答 1

使用IPython显示器在笔记本中渲染PIL图像。

from PIL import Image               # to load images
from IPython.display import display # to display images

pil_im = Image.open('path/to/image.jpg')
display(pil_im)

Use IPython display to render PIL images in a notebook.

from PIL import Image               # to load images
from IPython.display import display # to display images

pil_im = Image.open('path/to/image.jpg')
display(pil_im)

回答 2

我发现这有效

# source: http://nbviewer.ipython.org/gist/deeplook/5162445
from io import BytesIO

from IPython import display
from PIL import Image


def display_pil_image(im):
   """Displayhook function for PIL Images, rendered as PNG."""

   b = BytesIO()
   im.save(b, format='png')
   data = b.getvalue()

   ip_img = display.Image(data=data, format='png', embed=True)
   return ip_img._repr_png_()


# register display func with PNG formatter:
png_formatter = get_ipython().display_formatter.formatters['image/png']
dpi = png_formatter.for_type(Image.Image, display_pil_image)

在此之后,我可以做:

pil_im

但这必须是单元格中的最后一行,print之后没有

I found that this is working

# source: http://nbviewer.ipython.org/gist/deeplook/5162445
from io import BytesIO

from IPython import display
from PIL import Image


def display_pil_image(im):
   """Displayhook function for PIL Images, rendered as PNG."""

   b = BytesIO()
   im.save(b, format='png')
   data = b.getvalue()

   ip_img = display.Image(data=data, format='png', embed=True)
   return ip_img._repr_png_()


# register display func with PNG formatter:
png_formatter = get_ipython().display_formatter.formatters['image/png']
dpi = png_formatter.for_type(Image.Image, display_pil_image)

After this I can just do:

pil_im

But this must be last line in cell, with no print after it


回答 3

案例python3

from PIL import Image
from IPython.display import HTML
from io import BytesIO
from base64 import b64encode

pil_im = Image.open('data/empire.jpg')
b = BytesIO()  
pil_im.save(b, format='png')
HTML("<img src='data:image/png;base64,{0}'/>".format(b64encode(b.getvalue()).decode('utf-8')))

case python3

from PIL import Image
from IPython.display import HTML
from io import BytesIO
from base64 import b64encode

pil_im = Image.open('data/empire.jpg')
b = BytesIO()  
pil_im.save(b, format='png')
HTML("<img src='data:image/png;base64,{0}'/>".format(b64encode(b.getvalue()).decode('utf-8')))

回答 4

使用枕头在jupyter中简单得多。

from PIL import Image
image0=Image.open('image.png')
image0

much simpler in jupyter using pillow.

from PIL import Image
image0=Image.open('image.png')
image0

回答 5

您可以使用PIL包中的Image类打开图像,并直接使用plt.imshow显示它。

# First import libraries.
from PIL import Image
import matplotlib.pyplot as plt

# The folliwing line is useful in Jupyter notebook
%matplotlib inline

# Open your file image using the path
img = Image.open(<path_to_image>)

# Since plt knows how to handle instance of the Image class, just input your loaded image to imshow method
plt.imshow(img)

You can open an image using the Image class from the package PIL and display it with plt.imshow directly.

# First import libraries.
from PIL import Image
import matplotlib.pyplot as plt

# The folliwing line is useful in Jupyter notebook
%matplotlib inline

# Open your file image using the path
img = Image.open(<path_to_image>)

# Since plt knows how to handle instance of the Image class, just input your loaded image to imshow method
plt.imshow(img)

回答 6

如果使用pylab扩展,则可以将图像转换为numpy数组,并使用matplotlib的imshow。

%pylab # only if not started with the --pylab option
imshow(array(pil_im))

编辑:如评论中所述,不推荐使用pylab模块,因此请改用matplotlib magic并显式导入函数:

%matplotlib
from matplotlib.pyplot import imshow 
imshow(array(pil_im))

If you are using the pylab extension, you could convert the image to a numpy array and use matplotlib’s imshow.

%pylab # only if not started with the --pylab option
imshow(array(pil_im))

EDIT: As mentioned in the comments, the pylab module is deprecated, so use the matplotlib magic instead and import the function explicitly:

%matplotlib
from matplotlib.pyplot import imshow 
imshow(array(pil_im))

回答 7

根据其他答案和我的尝试,最好的经验是,首先安装,枕头和scipy,然后在jupyter笔记本上使用以下起始代码:

%matplotlib inline
from matplotlib.pyplot import imshow
from scipy.misc import imread

imshow(imread('image.jpg', 1))

Based on other answers and my tries, best experience would be first installing, pillow and scipy, then using the following starting code on your jupyter notebook:

%matplotlib inline
from matplotlib.pyplot import imshow
from scipy.misc import imread

imshow(imread('image.jpg', 1))

回答 8

使用标准numpy,matplotlib和PIL的更干净的Python3版本。合并从URL打开的答案。

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

回答 9

我建议以下安装时不要显示任何图像show img.show()(来自PIL导入图像)

$ sudo apt-get install imagemagick

I suggest following installation by no image show img.show() (from PIL import Image)

$ sudo apt-get install imagemagick


回答 10

只需使用

from IPython.display import Image 
Image('image.png')

Just use

from IPython.display import Image 
Image('image.png')