标签归档:jupyter-notebook

如何在Jupyter Notebook中获得自动完成功能而不使用制表符?

问题:如何在Jupyter Notebook中获得自动完成功能而不使用制表符?

我想在笔记本中获得自动完成功能,即当我键入内容时,会出现一个下拉菜单,其中包含我可能键入的所有可能内容,而无需按Tab键。有这样的事吗?

我试过了 :

%config IPCompleter.greedy =真实

但这需要按下选项卡按钮

I would like to get an autocompletion feature in notebooks i.e. when I type something, a dropdown menu appears, with all the possible things I might type, without having to press the tab button. Is there such a thing?

I tried :

%config IPCompleter.greedy=True

but this requires the tab button to be pressed


回答 0

有一个扩展名为Hinterland juterter的,在键入时会自动显示下拉菜单。还有一些其他有用的扩展。

为了安装扩展,您可以按照此github repo上的指南进行操作。要轻松激活扩展程序,您可能需要使用扩展程序配置器

There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.

In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.


回答 1

即使使用了腹地扩展,使用Jupyter Notebook的自动完成功能也是如此弱。感谢您提供基于深度学习的代码自动完成的想法。我开发了基于TabNine的Jupyter Notebook扩展,该扩展提供了基于深度学习的代码自动完成功能。这是我的工作的Github链接:jupyter-tabnine

现在可以在pypi索引上使用。只需发出以下命令,然后使用它即可:)

pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine

The auto-completion with Jupyter Notebook is so weak, even with hinterland extension. Thanks for the idea of deep-learning-based code auto-completion. I developed a Jupyter Notebook Extension based on TabNine which provides code auto-completion based on Deep Learning. Here’s the Github link of my work: jupyter-tabnine.

It’s available on pypi index now. Simply issue following commands, then enjoy it:)

pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine


回答 2

如上面@physicsGuy所述,您可以使用内地扩展名。简单的步骤即可。

使用conda forge频道安装nbextension。只需在conda终端中运行以下命令:

conda install -c conda-forge jupyter_nbextensions_configurator

下一步启用腹地扩展。在conda终端中运行以下命令:

jupyter nbextension enable hinterland/hinterland

就这样,完成了。

As mentioned by @physicsGuy above, You can use the hinterland extension. Simple steps to do it.

Installing nbextension using conda forge channel. Simply run the below command in conda terminal:

conda install -c conda-forge jupyter_nbextensions_configurator

Next Step enabling the hinterland extension. Run the below command in conda terminal:

jupyter nbextension enable hinterland/hinterland

That’s it, done.


回答 3

这样%config IPCompleter.greedy=True导入诸如numpy或pandas之类的软件包后,无需执行此操作; import numpy as np import pandas as pd

然后输入,pd.然后点击选项卡按钮,它会弹出所有可能的方法,以非常简单直接地使用。

Without doing this %config IPCompleter.greedy=True after you import a package like numpy or pandas in this way; import numpy as np import pandas as pd.

Then you type in pd. then tap the tab button it brings out all the possible methods to use very easy and straight forward.


回答 4

我正在使用Jupiter Notebook 5.6.0。在这里,要获得自动提示,我只需输入至少一个字符后按Tab键即可。

 **Example:** Enter character `p` and hit Tab.

要在导入的库中获取方法和属性,请使用与Alice相同的Tab键

  import numpy as np

  np. --> Hit Tab key

I am using Jupiter Notebook 5.6.0. Here, to get autosuggestion I am just hitting Tab key after entering at least one character.

 **Example:** Enter character `p` and hit Tab.

To get the methods and properties inside the imported library use same Tab key with Alice

  import numpy as np

  np. --> Hit Tab key

回答 5

将以下内容添加到Jupyter Lab的键盘用户首选项中(设置->高级系统编辑器)

{
    "shortcuts":[
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-notebook",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
        }

    ]
}

Add the below to your keyboard user preferences on jupyter lab (Settings->Advanced system editor)

{
    "shortcuts":[
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-notebook",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
        }

    ]
}

如何腌制或存储Jupyter(IPython)笔记本会话以供以后使用

问题:如何腌制或存储Jupyter(IPython)笔记本会话以供以后使用

假设我正在Jupyter / Ipython笔记本中进行较大的数据分析,并且完成了大量耗时的计算。然后,由于某种原因,我必须关闭jupyter本地服务器I,但是我想稍后再进行分析,而不必再次进行所有耗时的计算。


我想什么爱做的是pickle或存储整个Jupyter会话(所有大熊猫dataframes,np.arrays,变量,…),所以我可以放心地关闭服务器知道我可以在完全相同的状态返回到我的会话之前。

从技术上讲甚至可行吗?有没有我忽略的内置功能?


编辑:根据这个答案,有一种%store 魔法应该是“轻型泡菜”。但是,您必须像这样手动存储变量:

#inside a ipython/nb session
foo = "A dummy string"
%store foo
关闭种子,重新启动内核#r
%store -r foo进行刷新
print(foo) # "A dummy string"

这与我想要的功能相当接近,但是由于必须手动执行并且无法区分不同的会话,因此它的用处不大。

Let’s say I am doing a larger data analysis in Jupyter/Ipython notebook with lots of time consuming computations done. Then, for some reason, I have to shut down the jupyter local server I, but I would like to return to doing the analysis later, without having to go through all the time-consuming computations again.


What I would like love to do is pickle or store the whole Jupyter session (all pandas dataframes, np.arrays, variables, …) so I can safely shut down the server knowing I can return to my session in exactly the same state as before.

Is it even technically possible? Is there a built-in functionality I overlooked?


EDIT: based on this answer there is a %store magic which should be “lightweight pickle”. However you have to store the variables manually like so:

#inside a ipython/nb session
foo = "A dummy string"
%store foo
closing seesion, restarting kernel
%store -r foo # r for refresh
print(foo) # "A dummy string"

which is fairly close to what I would want, but having to do it manually and being unable to distinguish between different sessions makes it less useful.


回答 0

我认为迪尔很好地回答了您的问题。

pip install dill

保存笔记本会话:

import dill
dill.dump_session('notebook_env.db')

恢复笔记本会话:

import dill
dill.load_session('notebook_env.db')

资源

I think Dill answers your question well.

pip install dill

Save a Notebook session:

import dill
dill.dump_session('notebook_env.db')

Restore a Notebook session:

import dill
dill.load_session('notebook_env.db')

Source


回答 1

(我宁愿评论而不愿将其作为实际答案,但我需要更多的声誉才能发表评论。)

您可以系统地存储大多数类似数据的变量。我通常要做的是将所有数据帧,数组等存储在pandas.HDFStore中。在笔记本的开头,声明

backup = pd.HDFStore('backup.h5')

然后在产生它们时存储任何新变量

backup['var1'] = var1

最后,可能是一个好主意

backup.close()

在关闭服务器之前。下次您想继续使用笔记本时:

backup = pd.HDFStore('backup.h5')
var1 = backup['var1']

说实话,我也更喜欢ipython Notebook中的内置功能。您不能以这种方式保存所有内容(例如,对象,连接),并且很难用大量样板代码来组织笔记本。

(I’d rather comment than offer this as an actual answer, but I need more reputation to comment.)

You can store most data-like variables in a systematic way. What I usually do is store all dataframes, arrays, etc. in pandas.HDFStore. At the beginning of the notebook, declare

backup = pd.HDFStore('backup.h5')

and then store any new variables as you produce them

backup['var1'] = var1

At the end, probably a good idea to do

backup.close()

before turning off the server. The next time you want to continue with the notebook:

backup = pd.HDFStore('backup.h5')
var1 = backup['var1']

Truth be told, I’d prefer built-in functionality in ipython notebook, too. You can’t save everything this way (e.g. objects, connections), and it’s hard to keep the notebook organized with so much boilerplate codes.


回答 2

这个问题涉及到:如何在IPython Notebook中进行缓存?

为了保存单个单元的结果,缓存魔术派上了用场。

%%cache longcalc.pkl var1 var2 var3
var1 = longcalculation()
....

重新运行笔记本时,将从高速缓存中加载此单元格的内容。

这不能完全回答您的问题,但是对于所有冗长的计算结果都可以快速恢复的情况,这可能就足够了。这对我来说是一个可行的解决方案,同时点击了笔记本顶部的“ run-all”按钮。

缓存魔法救不了整个笔记本的状态还没有。据我所知,还没有其他系统可以恢复“笔记本”。这将需要保存python内核的所有历史记录。加载笔记本电脑并连接到内核后,应加载此信息。

This question is related to: How to cache in IPython Notebook?

To save the results of individual cells, the caching magic comes in handy.

%%cache longcalc.pkl var1 var2 var3
var1 = longcalculation()
....

When rerunning the notebook, the contents of this cell is loaded from the cache.

This is not exactly answering your question, but it might be enough to when the results of all the lengthy calculations are recovered fast. This in combination of hitting the run-all button on top of the notebook is for me a workable solution.

The cache magic cannot save the state of a whole notebook yet. To my knowledge there is no other system yet to resume a “notebook”. This would require to save all the history of the python kernel. After loading the notebook, and connecting to a kernel, this information should be loaded.


Recommenders-推荐系统的最佳实战教程

Recommenders现在在PyPI上,可以使用pip安装!此外,还有大量的错误修复和实用程序改进

您可以在此处找到PyPI页面:https://pypi.org/project/ms-recommenders/

您可以在此处找到软件包文档:https://microsoft-recommenders.readthedocs.io/en/latest/

引言

此存储库包含构建推荐系统的示例和最佳实践,以Jupyter笔记本形式提供。这些示例详细介绍了我们在五项关键任务上的学习:

中提供了几个实用程序reco_utils以支持常见任务,例如以不同算法预期的格式加载数据集、评估模型输出以及拆分训练/测试数据。其中包括几种最先进算法的实现,以便在您自己的应用程序中进行自学和自定义。请参阅reco_utils documentation

有关存储库的更详细概述,请参阅wiki page

快速入门

请参阅setup guide有关在本地设置计算机的更多详细信息,请访问data science virtual machine (DSVM)或打开Azure Databricks

推荐器软件包的安装已经过Python版本3.6和3.7的测试。建议在干净的环境中安装软件包及其依赖项(例如condavenv)

要在本地计算机上进行设置,请执行以下操作:

要安装核心实用程序、基于CPU的算法和相关性,请执行以下操作:

  1. 确保安装了编译所需的软件。在Linux上,可以通过添加构建基本依赖项来支持这一点:
sudo apt-get install -y build-essential

在Windows上,您需要Microsoft C++ Build Tools

  1. 从以下位置安装软件包PyPI
pip install --upgrade pip
pip install ms-recommenders[examples]
  1. 向Jupyter注册您的(CONDA或虚拟)环境:
python -m ipykernel install --user --name my_environment_name --display-name "Python (reco)"
  1. 启动Jupyter笔记本服务器
jupyter notebook
  1. 运行SAR Python CPU MovieLens笔记本在下面00_quick_start文件夹。确保将内核更改为“Python(Reco)”

有关安装软件包的其他选项(支持图形处理器、电光等)看见this guide

注意事项-TheAlternating Least Squares (ALS)笔记本电脑需要PySpark环境才能运行。请按照中的步骤操作setup guide在PySpark环境中运行这些笔记本。对于深度学习算法,建议使用GPU机器,并遵循setup guide要设置NVIDIA库,请执行以下操作

算法

下表列出了存储库中当前可用的推荐算法。当有不同的实施可用时,笔记本将链接在环境列下

算法 环境 类型 描述
交替最小二乘(ALS) PySpark 协同过滤 大数据集中显式或隐式反馈的矩阵分解算法,电光MLLib针对可扩展性和分布式计算能力进行了优化
关注异步奇异值分解(A2SVD)* Python CPU / Python GPU 协同过滤 一种基于顺序的算法,旨在利用注意力机制捕获长期和短期用户偏好
CONAC/贝叶斯个性化排名(BPR) Python CPU 协同过滤 隐式反馈预测项目排序的矩阵分解算法
角/双边变分自动编码器(BiVAE) Python CPU / Python GPU 协同过滤 二元数据的生成模型(例如,用户-项目交互)
卷积序列嵌入推荐(CASER) Python CPU / Python GPU 协同过滤 基于卷积的算法,旨在捕获用户的一般偏好和序列模式
深度知识感知网络(DKN)* Python CPU / Python GPU 基于内容的过滤 包含知识图和文章嵌入的深度学习算法,可提供强大的新闻或文章推荐
极深因式分解机(XDeepFM)* Python CPU / Python GPU 混血儿 基于深度学习的具有用户/项目特征的隐式和显式反馈算法
FastAI嵌入点偏置(FAST) Python CPU / Python GPU 协同过滤 面向用户和项目的带嵌入和偏向的通用算法
LightFM/混合矩阵分解 Python CPU 混血儿 隐式和显式反馈的混合矩阵分解算法
LightGBM/渐变增强树* Python CPU/PySpark 基于内容的过滤 基于内容问题的快速训练和低内存占用的梯度Boosting树算法
LightGCN Python CPU / Python GPU 协同过滤 一种深度学习算法,简化了隐式反馈预测GCN的设计
GeoIMC* Python CPU 混血儿 矩阵补全算法,考虑了用户和项目的特点,使用黎曼共轭梯度优化,遵循几何方法
GRU4Rec Python CPU / Python GPU 协同过滤 基于序列的算法,旨在使用递归神经网络捕获长期和短期用户偏好
多项式VAE Python CPU / Python GPU 协同过滤 预测用户/项目交互的产生式模型
具有长期和短期用户表示的神经推荐(LSTUR)* Python CPU / Python GPU 基于内容的过滤 具有长期和短期用户兴趣建模的神经推荐算法
基于注意力多视图学习(NAML)的神经推荐* Python CPU / Python GPU 基于内容的过滤 具有注意力多视角学习的神经推荐算法
神经协同过滤(NCF) Python CPU / Python GPU 协同过滤 一种性能增强的隐式反馈深度学习算法
具有个性化注意的神经推荐(NPA)* Python CPU / Python GPU 基于内容的过滤 基于个性化注意力网络的神经推荐算法
基于多头自我注意(NRMS)的神经推荐* Python CPU / Python GPU 基于内容的过滤 一种多头自关注的神经推荐算法
下一项推荐(NextItNet) Python CPU / Python GPU 协同过滤 基于扩张卷积和残差网络的序列模式捕获算法
受限Boltzmann机器(RBM) Python CPU / Python GPU 协同过滤 基于神经网络的显式或隐式反馈潜在概率分布学习算法
黎曼低秩矩阵完成(RLRMC)* Python CPU 协同过滤 基于黎曼共轭梯度优化的小内存矩阵分解算法
简单推荐算法(SAR)* Python CPU 协同过滤 基于相似度的隐式反馈数据集算法
短期和长期偏好综合推荐(SLI-REC)* Python CPU / Python GPU 协同过滤 基于顺序的算法,旨在使用注意机制、时间感知控制器和内容感知控制器捕获长期和短期用户偏好
多兴趣感知的序贯用户建模(SUM)* Python CPU / Python GPU 协同过滤 一种旨在捕捉用户多兴趣的增强型记忆网络顺序用户模型
标准VAE Python CPU / Python GPU 协同过滤 预测用户/项目交互的产生式模型
奇异值分解(SVD) Python CPU 协同过滤 预测不是很大数据集中显式评级反馈的矩阵分解算法
术语频率-文档频率反转(TF-IDF) Python CPU 基于内容的过滤 一种简单的基于相似度的文本数据内容推荐算法
Vowpal Wabbit(大众)* Python CPU (online training) 基于内容的过滤 快速在线学习算法,非常适合用户功能/上下文不断变化的场景
宽而深 Python CPU / Python GPU 混血儿 一种可记忆特征交互和泛化用户特征的深度学习算法
xLearch/factorization Machine(FM)&场感知FM(FFM) Python CPU 混血儿 利用用户/项目特征预测标签的快速高效内存算法

注意事项*指示由Microsoft发明/贡献的算法

独立的或正在孵化的算法和实用程序是contrib文件夹。这将包含可能不容易放入核心存储库的贡献,或者需要时间来重构或成熟代码并添加必要的测试

算法 环境 类型 描述
SARplus* PySpark 协同过滤 电光合成孔径雷达的优化实现

初步比较

我们提供一个benchmark notebook以说明如何评估和比较不同的算法。在本笔记本中,使用分层拆分将MovieLens数据集按75/25的比率拆分成训练/测试集。使用下面的每个协同过滤算法来训练推荐模型。我们利用文献中报道的经验参数值。here在对指标进行排名时,我们使用k=10(前十大推荐项目)。我们在标准NC6S_v2上运行比较Azure DSVM(6个vCPU、112 GB内存和1个P100 GPU)。电光肌萎缩侧索硬化症在本地独立模式下运行。在此表中,我们显示了在Movielens 100k上运行15个时期的算法的结果

算法 地图 nDCG@k 精度@k Recall@k RMSE Mae R2个 解释的差异
ALS 0.004732 0.044239 0.048462 0.017796 0.965038 0.753001 0.255647 0.251648
BiVAE 0.146126 0.475077 0.411771 0.219145 不适用 不适用 不适用 不适用
BPR 0.132478 0.441997 0.388229 0.212522 不适用 不适用 不适用 不适用
FastAI 0.025503 0.147866 0.130329 0.053824 0.943084 0.744337 0.285308 0.287671
LightGCN 0.088526 0.419846 0.379626 0.144336 不适用 不适用 不适用 不适用
NCF 0.107720 0.396118 0.347296 0.180775 不适用 不适用 不适用 不适用
SAR 0.110591 0.382461 0.330753 0.176385 1.253805 1.048484 -0.569363 0.030474
SVD 0.012873 0.095930 0.091198 0.032783 0.938681 0.742690 0.291967 0.291971

行为规范

本项目坚持Microsoft’s Open Source Code of Conduct为了给所有人营造一个欢迎和鼓舞人心的社区

贡献

这个项目欢迎大家提供意见和建议。在投稿之前,请查看我们的contribution guidelines

生成状态

这些测试是夜间构建,用于计算冒烟和集成测试。main是我们的主要分支机构staging是我们的发展分部。我们使用pytest中测试python实用程序reco_utilspapermill对于notebooks有关测试管道的更多信息,请参阅test documentation

DSVM构建状态

以下测试每天在Linux DSVM上运行。这些机器全天候运转。

构建类型 分支机构 状态 分支机构 状态
Linux CPU 主干道 试运行
Linux GPU 主干道 试运行
LINUX电光 主干道 试运行

相关项目

参考文献

  • A.Argyriou、M.González-Fierro和L.Zhang,“Microsoft推荐器:可投入生产的推荐系统的最佳实践(Best Practices for Production-Ready Recommendation Systems)”,万维网2020:台北国际万维网大会,2020年。在线提供:https://dl.acm.org/doi/abs/10.1145/3366424.3382692
  • 张立,吴涛,谢,A.Argyriou,M.González-Fierro,J.Lian,“建立规模化的可生产推荐系统”,ACM SIGKDD 2019年知识发现和数据挖掘大会(KDD 2019),2019年
  • S.Graham,J.K.Min,T.Wu,“微软推荐器:加速开发推荐器系统的工具”,RecSys‘19:第13届ACM推荐系统会议论文集,2019年。在线提供:https://dl.acm.org/doi/10.1145/3298689.3346967

如何与非程序员共享Jupyter笔记本?[关闭]

问题:如何与非程序员共享Jupyter笔记本?[关闭]

我试图用Jupyter做我不能做的事情。

我的内部服务器上运行着Jupyter服务器,可通过VPN和受密码保护的服务器进行访问。

我是唯一实际创建笔记本的人,但是我想以只读方式使其他团队成员可以看到一些笔记本。理想情况下,我可以与他们共享一个URL,当他们希望查看带有刷新数据的笔记本时,他们将为其添加书签。

我看到了导出选项,但找不到任何有关“发布”或“公开”本地现场笔记本的信息。这不可能吗?考虑应该如何使用Jupyter可能只是错误的方式?

I am trying to wrap my head around what I can/cannot do with Jupyter.

I have a Jupyter server running on our internal server, accessible via VPN and password protected.

I am the only one actually creating notebooks but I would like to make some notebooks visible to other team members in a read-only way. Ideally I could just share a URL with them that they would bookmark for when they want to see the notebook with refreshed data.

I saw export options but cannot find any mention of “publishing” or “making public” local live notebooks. Is this impossible? Is it maybe just a wrong way to think about how Jupyter should be used?


回答 0

共享Jupyter笔记本的“最佳”方法是将其放置在GitHub(直接查看)或其他公共链接上,然后使用Jupyter Notebook Viewer。当隐私更多是一个问题时,可以有其他选择,但肯定会更复杂。仅Jupyter并没有内置的方法来执行此操作,但是有两个选项:

托管您自己的nbviewer

GitHub和Jupyter Notebook Veiwer都使用相同的工具将.ipynb文件呈现为静态HTML,此工具为nbviewer

安装说明比我愿意介绍的要复杂,但是如果您的公司/团队拥有不需要密码访问的共享服务器,则可以在该服务器上托管nbviewer并指示其从您的凭据服务器加载。这可能需要比您将在文档中找到的配置更高级的配置。

设置部署脚本

如果您不一定需要实时更新HTML,则可以在有证书的服务器上设置一个脚本,该脚本将仅使用Jupyter的内置导出选项来创建静态HTML文件,然后将其发送到更易于访问的服务器上。

The “best” way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the Jupyter Notebook Viewer. When privacy is more of an issue then there are alternatives but it’s certainly more complex; there’s no built-in way to do this in Jupyter alone, but a couple of options are:

Host your own nbviewer

GitHub and the Jupyter Notebook Veiwer both use the same tool to render .ipynb files into static HTML, this tool is nbviewer.

The installation instructions are more complex than I’m willing to go into here but if your company/team has a shared server that doesn’t require password access then you could host the nbviewer on that server and direct it to load from your credentialed server. This will probably require some more advanced configuration than you’re going to find in the docs.

Set up a deployment script

If you don’t necessarily need live updating HTML then you could set up a script on your credentialed server that will simply use Jupyter’s built-in export options to create the static HTML files and then send those to a more publicly accessible server.


回答 1

Google最近公开了其内部协作项目(此处链接)。您可以使用与启动Google表格或Google文档相同的方式来启动笔记本,然后简单地共享笔记本或添加协作者。

目前,这对我来说是最简单的方法。

Google has recently made public its internal Collaboratory project (link here). You can start a notebook in the same way as starting a Google Sheet or Google Doc, and then simply share the notebook or add collaborators..

For now, this is the easiest way for me.


回答 2

迈克尔建议运行自己的nbviewer实例是我过去在Enterprise Github服务器上使用的一个很好的建议。

另一个轻量级替代方法是在笔记本的末尾有一个单元格,该单元格对nbconvert进行shell调用,以便在运行整个过程后自动刷新该单元格:

!ipython nbconvert <notebook name>.ipynb --to html

编辑:使用Jupyter / IPython的Big Split,您可能需要将其更改为!jupyter nbconvert <notebook name>.ipynb --to html现在。

Michael’s suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it’s automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython’s Big Split, you’ll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.


回答 3

这取决于您打算如何使用笔记本电脑:您是否希望用户可以重新计算结果或只是玩游戏?

静态笔记本

NBViewer是一个很棒的工具。您可以在Jupyter中直接使用它。Github也有一个渲染器,因此您可以直接链接文件(例如https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb

活着的笔记本

如果希望用户能够重新计算某些部分,则也可以使用MyBinder。启动笔记本需要花费一些时间,但是这样做值得。

正如@Mapl称,谷歌可以承载您的笔记本Colab。一项不错的功能是通过GPU计算单元。

It depends on what you are intending to do with your Notebook: do you want that the user can recompute the results or just playing with them?

Static notebook

NBViewer is a great tool. You can directly use it inside Jupyter. Github has also a render, so you can directly link your file (such as https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb)

Alive notebook

If you want your user to be able to recompute some parts, you can also use MyBinder. It takes some time to start your notebook, but the result is worth it.

As said by @Mapl, Google can host your notebook with Colab. A nice feature is to compute your cells over a GPU.


回答 4

在WordPress上执行此操作的一种好方法包括以下步骤:

步骤1:在文本编辑器中打开Jupyter笔记本,然后复制内容,如下所示: 在文本编辑器中打开您的.ipynb文件时,可能看起来像这样

步骤2: 按Ctrl + ACtrl + C此内容。然后按Ctrl + V到您应该创建的GitHub Gist。

第3步:创建公共要点,然后像通常将要点要嵌入到WordPress一样,将要点嵌入,请转到HTML编辑器并按如下所示添加:

[gist gist_url]

我实际上已经在我的博客上实现了此功能。你可以在这里找到帖子

A great way of doing this on WordPress consists of the following steps:

Step 1: Open your Jupyter notebook in a text editor and copy the content which may look like so: Your .ipynb file may look like this when opened in a text editor

Step 2: Ctrl + A and Ctrl + C this content. Then Ctrl + V this to a GitHub Gist that you should create.

Step 3: Create a public gist and embed the gist like you always embed gists on WordPress, viz., go to the HTML editor and add like so:

[gist gist_url]

I have actually implemented this on my blog. You can find the post here


回答 5

实现此目标的一种方法是使用JupyterHub

使用JupyterHub,您可以创建一个多用户中心,该中心可以生成,管理和代理单用户Jupyter笔记本服务器的多个实例。由于其灵活性和定制选项,JupyterHub可用于为学生,公司数据科学小组或科研小组的笔记本电脑提供服务。

One more way to achieve this goal would be using JupyterHub.

With JupyterHub you can create a multi-user Hub which spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server. Due to its flexibility and customization options, JupyterHub can be used to serve notebooks to a class of students, a corporate data science group, or a scientific research group.


如何从终端运行.ipynb Jupyter Notebook?

问题:如何从终端运行.ipynb Jupyter Notebook?

我在.ipynb文件中有一些代码,并且到了我真的不需要IPython Notebook的“交互”功能的地步。我想直接从Mac Terminal命令行运行它。

基本上,如果这只是一个.py文件,我相信我可以从命令行执行python filename.py。.ipynb文件是否存在类似内容?

I have some code in a .ipynb file and got it to the point where I don’t really need the “interactive” feature of IPython Notebook. I would like to just run it straight from a Mac Terminal Command Line.

Basically, if this were just a .py file, I believe I could just do python filename.py from the command line. Is there something similar for a .ipynb file?


回答 0

在命令行中,您可以使用以下命令将笔记本转换为python:

jupyter nbconvert --to python nb.ipynb

https://github.com/jupyter/nbconvert

您可能需要安装python mistune软件包:

sudo pip install -U mistune

From the command line you can convert a notebook to python with this command:

jupyter nbconvert --to python nb.ipynb

https://github.com/jupyter/nbconvert

You may have to install the python mistune package:

sudo pip install -U mistune

回答 1

nbconvert允许您运行带有--execute标志的笔记本:

jupyter nbconvert --execute <notebook>

如果您想运行一个笔记本并生产一个新的笔记本,则可以添加--to notebook

jupyter nbconvert --execute --to notebook <notebook>

或者,如果您想用新的输出替换现有的笔记本:

jupyter nbconvert --execute --to notebook --inplace <notebook>

由于这是一个很长的命令,因此可以使用别名:

alias nbx="jupyter nbconvert --execute --to notebook"
nbx [--inplace] <notebook>

nbconvert allows you to run notebooks with the --execute flag:

jupyter nbconvert --execute <notebook>

If you want to run a notebook and produce a new notebook, you can add --to notebook:

jupyter nbconvert --execute --to notebook <notebook>

Or if you want to replace the existing notebook with the new output:

jupyter nbconvert --execute --to notebook --inplace <notebook>

Since that’s a really long command, you can use an alias:

alias nbx="jupyter nbconvert --execute --to notebook"
nbx [--inplace] <notebook>

回答 2

您可以从中导出所有代码.ipynb并将其另存为.py脚本。然后,您可以在终端中运行脚本。

希望能帮助到你。

You can export all your code from .ipynb and save it as a .py script. Then you can run the script in your terminal.

Hope it helps.


回答 3

在终端中运行ipython:

ipython

然后找到您的脚本并放在此处:

%run your_script.ipynb

In your Terminal run ipython:

ipython

then locate your script and put there:

%run your_script.ipynb

回答 4

对于新版本,而不是:

ipython nbconvert --to python <YourNotebook>.ipynb

您可以使用ipython的jupyter实例:

jupyter nbconvert --to python <YourNotebook>.ipynb

For new version instead of:

ipython nbconvert --to python <YourNotebook>.ipynb

You can use jupyter instend of ipython:

jupyter nbconvert --to python <YourNotebook>.ipynb

回答 5

更新作者引用的评论,以提高可见度:

作者注释:“该项目在Jupyter的执行API之前启动,现在是从命令行运行笔记本的推荐方式。请考虑弃用不维护runipy的软件。” –塞巴斯蒂安·帕尔马(Sebastian Palma)

安装允许在终端上运行代码的runipy库

pip install runipy

只是编译您的代码后:

runipy <YourNotebookName>.ipynb

您也可以尝试cronjob。所有信息都在这里

Update with quoted comment by author for better visibility:

Author’s note “This project started before Jupyter’s execute API, which is now the recommended way to run notebooks from the command-line. Consider runipy deprecated and unmaintained.” – Sebastian Palma

Install runipy library that allows running your code on terminal

pip install runipy

After just compiler your code:

runipy <YourNotebookName>.ipynb

You can try cronjob as well. All information is here


回答 6

就我而言,最适合我的命令是:

jupyter nbconvert --execute --clear-output <notebook>.ipynb

为什么?此命令不会创建额外的文件(就像.py文件一样),并且每次执行Notebook时,单元的输出都会被覆盖。

如果您运行:

jupyter nbconvert --help

–clear-output清除当前文件的输出并保存到位,覆盖现有笔记本。

In my case, the command that best suited me was:

jupyter nbconvert --execute --clear-output <notebook>.ipynb

Why? This command does not create extra files (just like a .py file) and the output of the cells is overwritten everytime the notebook is executed.

If you run:

jupyter nbconvert --help

–clear-output Clear output of current file and save in place, overwriting the existing notebook.


回答 7

您还可以使用该boar软件包在python代码中运行笔记本。

from boar.running import run_notebook

outputs = run_notebook("nb.ipynb")

如果更新笔记本,则无需再次将其转换为python文件。


有关更多信息,请访问:

https://github.com/alexandreCameron/boar/blob/master/USAGE.md

You can also use the boar package to run your notebook within a python code.

from boar.running import run_notebook

outputs = run_notebook("nb.ipynb")

If you update your notebook, you won’t have to convert it again to a python file.


More information at:

https://github.com/alexandreCameron/boar/blob/master/USAGE.md


回答 8

从终端运行

jupyter nbconvert --execute --to notebook --inplace --allow-errors --ExecutePreprocessor.timeout=-1 my_nb.ipynb

默认超时为30秒。-1消除了限制。

如果您希望将输出笔记本保存到新笔记本中,则可以使用该标志 --output my_new_nb.ipynb

From the terminal run

jupyter nbconvert --execute --to notebook --inplace --allow-errors --ExecutePreprocessor.timeout=-1 my_nb.ipynb

The default timeout is 30 seconds. -1 removes the restriction.

If you wish to save the output notebook to a new notebook you can use the flag --output my_new_nb.ipynb


回答 9

我有同样的问题,我找到了造纸厂。与其他解决方案相比的优势在于,您可以在笔记本计算机运行时看到结果。当笔记本电脑花费很长时间时,我发现此功能很有趣。这是非常容易使用:

pip install papermill
papermill notebook.ipynb output.ipynb

它还具有其他方便的选项,例如将输出文件保存到Amazon S3,Google Cloud等。有关更多信息,请参阅页面。

I had the same problem and I found papermill. The advantages against the others solutions is that you can see the results while the notebook is running. I find this feature interesting when the notebook takes very long. It is very easy to use:

pip install papermill
papermill notebook.ipynb output.ipynb

It has also, other handy options as saving the output file to Amazon S3, Google Cloud, etc. See the page for more information.


如何在IPython Notebook Server 3中看到函数参数?

问题:如何在IPython Notebook Server 3中看到函数参数?

我最近切换到了Anaconda版本的IPython Notebook 3(确切地说是3.1.0-cbccb68)。以前,当我键入一个函数并打开一个这样的括号时:

time.sleep()

如果光标在括号之间,那么我将获得一个显示功能参数的上下文覆盖菜单。现在,我没有看到它,尽管已经搜索了,但仍然找不到如何打开此功能的方法。

I’ve recently switched to IPython Notebook 3 (3.1.0-cbccb68 to be exact), the Anaconda version. Previously when I typed a function and opened a parenthesis like this:

time.sleep()

and if the cursor was between the parentheses then I would get a contextual overlay menu that displayed the function arguments. Now I don’t see it, and although I’ve searched, I can’t find out how I can turn on this functionality.


回答 0

在1.0中,该功能被绑定到(tabshift-tab,在2.0 tab被废弃,但仍具有功能在某些情况下,明确的完成或检查在许多情况下被竞争。建议始终使用shift-Tab(在类似Haskell的语法中,它也被添加为令人讨厌的不推荐使用,因为它在更多情况下也可以将人们推向Shift-Tab。在3.0中,已弃用的绑定已被删除,以支持正式发布,现在已存在18个月以上Shift-Tab

因此按Shift-Tab

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.


回答 1

尝试Shift-Tab-Tab使用比更大的文档Shift-Tab。一样,但是您可以向下滚动。

Shift-Tab-Tab-Tab 在您输入时,工具提示会持续10秒钟。

Shift-Tab-Tab-Tab-Tab 并且文档字符串出现在寻呼机中(窗口底部的一小部分)并停留在该位置。

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It’s the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.


回答 2

为@Thomas G的答案添加屏幕截图(示例)和更多上下文。

如果它不起作用,请确保您已经正确执行了代码。在这种情况下,请确保import pandas as pd已正确运行,然后再检查以下快捷方式。

()使用快捷方式之前,请将光标放在括号的中间。

shift + tab

显示简短的文档和少量参数

shift + tab + tab

使用滚动条扩展文档

shift + tab + tab + tab

提供带有工具提示的文档:“您键入时会停留10秒钟”。这意味着您可以编写参数并等待10秒。

shift + tab + tab + tab + tab

它在底部打开一个带有选项的小窗口(小窗口的右上角),以在新的浏览器选项卡中打开完整的文档。

Adding screen shots(examples) and some more context for the answer of @Thomas G.

if its not working please make sure if you have executed code properly. In this case make sure import pandas as pd is ran properly before checking below shortcut.

Place the cursor in middle of parenthesis () before you use shortcut.

shift + tab

Display short document and few params

shift + tab + tab

Expands document with scroll bar

shift + tab + tab + tab

Provides document with a Tooltip: “will linger for 10secs while you type”. which means it allows you write params and waits for 10secs.

shift + tab + tab + tab + tab

It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.


回答 3

Shift-Tab可让我查看产品

Shift-Tab works for me to view the dcoumentation


如何将HTML嵌入IPython输出中?

问题:如何将HTML嵌入IPython输出中?

是否可以将呈现的HTML输出嵌入到IPython输出中?

一种方法是使用

from IPython.core.display import HTML
HTML('<a href="http://example.com">link</a>')

或(IPython多行单元格别名)

%%html
<a href="http://example.com">link</a>

哪个返回格式化的链接,但是

  1. 此链接不会从控制台打开带有网页本身的浏览器。不过,IPython笔记本支持诚实渲染。
  2. 我不知道如何HTML()在列表或pandas打印表中呈现对象。您可以这样做df.to_html(),但无需在单元格内建立链接。
  3. 此输出在PyCharm Python控制台中不是交互式的(因为它不是QT)。

如何克服这些缺点并使IPython输出更具交互性?

Is it possible to embed rendered HTML output into IPython output?

One way is to use

from IPython.core.display import HTML
HTML('<a href="http://example.com">link</a>')

or (IPython multiline cell alias)

%%html
<a href="http://example.com">link</a>

Which return a formatted link, but

  1. This link doesn’t open a browser with the webpage itself from the console. IPython notebooks support honest rendering, though.
  2. I’m unaware of how to render HTML() object within, say, a list or pandas printed table. You can do df.to_html(), but without making links inside cells.
  3. This output isn’t interactive in the PyCharm Python console (because it’s not QT).

How can I overcome these shortcomings and make IPython output a bit more interactive?


回答 0

这似乎为我工作:

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

诀窍是也将其包装在“显示”中。

来源:http : //python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html

This seems to work for me:

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

The trick is to wrap it in “display” as well.

Source: http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html


回答 1

一段时间以前,Jupyter Notebooks开始从HTML内容中剥离JavaScript [ #3118 ]。这是两个解决方案:

提供本地HTML

如果要立即在页面上嵌入带有JavaScript的HTML页面,最简单的方法是使用笔记本将HTML文件保存到目录中,然后按以下方式加载HTML:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

提供远程HTML

如果您喜欢托管解决方案,则可以在S3中将HTML页面上传到Amazon Web Services“存储桶”,更改该存储桶上的设置,以使该存储桶托管静态网站,然后在笔记本中使用Iframe组件:

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

就像在其他任何网页上一样,这将在iframe中呈现HTML内容和JavaScript:

<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>

Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:

Serving Local HTML

If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

Serving Remote HTML

If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services “bucket” in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:

<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>

回答 2

相关:在构造类时,def _repr_html_(self): ...可用于创建其实例的自定义HTML表示形式:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

将呈现为:

世界你好!

有关更多信息,请参阅IPython的文档

一个高级示例:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "☑" if item['completed'] else "☐",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

将呈现:

  1. ☐购买牛奶
  2. ☐做作业
  3. ☑玩电子游戏

Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

will render as:

Hello World!

For more info refer to IPython’s docs.

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "☑" if item['completed'] else "☐",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

Will render:

  1. ☐ Buy milk
  2. ☐ Do homework
  3. ☑ Play video games

回答 3

在上面的@Harmon上展开,看来您可以将displayand print语句组合在一起……如果需要的话。或者,将整个HTML格式化为一个字符串然后使用显示可能会更容易。无论哪种方式,不错的功能。

display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))

输出如下所示:


你好,世界!

这里是一个链接:

www.google.com

一些更多的印刷文字…

此处的段落文字…


Expanding on @Harmon above, looks like you can combine the display and print statements together … if you need. Or, maybe it’s easier to just format your entire HTML as one string and then use display. Either way, nice feature.

display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))

Outputs something like this:


Hello, world!

Here’s a link:

www.google.com

some more printed text …

Paragraph text here …



尝试运行Python脚本时出现“ ImportError:未命名模块”

问题:尝试运行Python脚本时出现“ ImportError:未命名模块”

我正在尝试运行一个脚本,该脚本除其他外将启动python脚本。我收到一个ImportError:没有名为…的模块,但是,如果我启动ipython并通过解释器以相同的方式导入相同的模块,则该模块将被接受。

怎么回事,我该如何解决?我试图了解python如何使用PYTHONPATH,但是我感到非常困惑。任何帮助将不胜感激。

I’m trying to run a script that launches, amongst other things, a python script. I get a ImportError: No module named …, however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted.

What’s going on, and how can I fix it? I’ve tried to understand how python uses PYTHONPATH but I’m thoroughly confused. Any help would greatly appreciated.


回答 0

由于命令行IPython解释器使用当前路径的方式与单独进程(例如IPython笔记本,外部进程等)的方式不同,因此会出现此问题。IPython将寻找要导入的模块,这些模块不仅可以在sys.path中找到,而且可以在当前工作目录中找到。从命令行启动解释器时,您正在操作的当前目录与在ipython中启动的目录相同。如果运行

import os
os.getcwd() 

您会看到这是真的。

但是,假设您使用的是ipython笔记本,请运行,os.getcwd()而当前的工作目录是您告诉笔记本在ipython_notebook_config.py文件中操作笔记本的文件夹(通常使用该c.NotebookManager.notebook_dir设置)。

解决方案是为python解释器提供您的模块路径。最简单的解决方案是将该路径附加到sys.path列表中。在您的笔记本中,首先尝试:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

如果这不起作用,则您手上的问题与导入路径无关,您应提供有关问题的更多信息。

解决此问题的更好(且更永久)的方法是设置PYTHONPATH,它为解释器提供了用于python包/模块的其他目录。将PYTHONPATH编辑或设置为全局变量是os依赖的,这里将在UnixWindows上进行详细讨论。

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you’re operating in is the same one you started ipython in. If you run

import os
os.getcwd() 

you’ll see this is true.

However, let’s say you’re using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

If that doesn’t work, you’ve got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.


回答 1

__init__.py运行python项目时,只需在显示错误的文件夹下创建一个名称为空的python文件即可。

Just create an empty python file with the name __init__.py under the folder which showing error, while you running the python project.


回答 2

确保它们都使用相同的解释器。这在Ubuntu上发生在我身上:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

而且sys.path是两个解释不同。为了解决这个问题,我删除了Python 3.3。

Make sure they are both using the same interpreter. This happened to me on Ubuntu:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

And sys.path was different between the two interpreters. To fix it, I removed Python 3.3.


回答 3

主要原因是Python和IPython的sys.paths不同。

请参考lucypark链接,该解决方案适用于我的情况。它通过安装opencv时发生

conda install opencv

在iPython中出现导入错误,有三个步骤可以解决此问题:

import cv2
ImportError: ...

1.使用以下命令检查Python和iPython中的路径

import sys
sys.path

您会发现与Python和Jupyter不同的结果。第二步,只需使用sys.path.append 尝试错误即可修复错过的路径。

2.临时解决方案

在iPython中:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

ImportError:..问题的解决

3.永久解决方案

创建一个iPython配置文件并设置初始追加:

在bash shell中:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

在vi中,附加到文件:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

完成

The main reason is the sys.paths of Python and IPython are different.

Please refer to lucypark link, the solution works in my case. It happen when install opencv by

conda install opencv

And got import error in iPython, There are three steps to solve this issue:

import cv2
ImportError: ...

1. Check path in Python and iPython with following command

import sys
sys.path

You will find different result from Python and Jupyter. Second step, just use sys.path.append to fix the missed path by try-and-error.

2. Temporary solution

In iPython:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

the ImportError:.. issue solved

3. Permanent solution

Create an iPython profile and set initial append:

In bash shell:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

In vi, append to the file:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

DONE


回答 4

这样做是sys.path.append('my-path-to-module-folder')可行的,但是为了避免每次要使用IMod时都必须在IPython中执行此操作,可以将其添加export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH"~/.bash_profile文件中。

Doing sys.path.append('my-path-to-module-folder') will work, but to avoid having to do this in IPython every time you want to use the module, you can add export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH" to your ~/.bash_profile file.


回答 5

在安装ipython之前,我通过easy_install安装了模块;说sudo easy_install mechanize

安装ipython之后,我必须重新运行easy_install才能使ipython识别模块。

Before installing ipython, I installed modules through easy_install; say sudo easy_install mechanize.

After installing ipython, I had to re-run easy_install for ipython to recognize the modules.


回答 6

遇到了类似的问题,通过调用python3而不是python进行了修复,我的模块在Python3.5中。

Had a similar problem, fixed it by calling python3 instead of python, my modules were in Python3.5.


回答 7

如果从命令行运行它,有时python解释器将不知道在何处查找模块。

下面是我的项目的目录结构:

/project/apps/..
/project/tests/..

我在以下命令下运行:

>> cd project

>> python tests/my_test.py

运行以上命令后,出现以下错误

no module named lib

lib已导入my_test.py

我打印了sys.path并发现我正在处理的项目的路径在sys.path列表中不可用

我在脚本的开头添加了以下代码my_test.py

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

我不确定这是否是解决问题的好方法,但是是的,它确实对我有用。

If you are running it from command line, sometimes python interpreter is not aware of the path where to look for modules.

Below is the directory structure of my project:

/project/apps/..
/project/tests/..

I was running below command:

>> cd project

>> python tests/my_test.py

After running above command i got below error

no module named lib

lib was imported in my_test.py

i printed sys.path and figured out that path of project i am working on is not available in sys.path list

i added below code at the start of my script my_test.py .

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

I am not sure if it is a good way of solving it but yeah it did work for me.


回答 8

这是我解决的方法:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

This is how I fixed it:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

回答 9

我发现此问题的解决方案已在此处广泛记录:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

基本上,您必须在Jupyter环境中安装软件包,并发出如下shell命令:

!{sys.executable} -m pip install numpy

请检查上面的链接以获得权威的完整答案。

I have found that the solution to this problem was extensively documented here:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

Basically, you must install the packages within the Jupyter environment, issuing shell commands like:

!{sys.executable} -m pip install numpy

Please check the above link for an authoritative full answer.


回答 10

我发现了这种差异的另一个来源:

我在本地和在virtualenvs中都安装了ipython。我的问题是,在使用ipython新建的virtualenv内部,安装了ipython系统,它与virtualenv中的python和ipython版本不同(2.7.x与3.5.x),并且随之而来。

我认为,每当安装将要安装二进制文件的东西时,明智的做法yourvirtualenv/binrehash针对正在使用的任何外壳程序立即运行或类似运行,以便获取正确的python / ipython。(必须检查是否有合适pip的安装后挂钩…)

I found yet another source of this discrepancy:

I have ipython installed both locally and in commonly in virtualenvs. My problem was that, inside a newly made virtualenv with ipython, the system ipython was picked up, which was a different version than the python and ipython in the virtualenv (a 2.7.x vs. a 3.5.x), and hilarity ensued.

I think the smart thing to do whenever installing something that will have a binary in yourvirtualenv/bin is to immediately run rehash or similar for whatever shell you are using so that the correct python/ipython gets picked up. (Gotta check if there are suitable pip post-install hooks…)


回答 11

不带脚本的解决方案:

  1. 打开Spyder->工具-> PYTHONPATH管理器
  2. 通过单击“添加路径”来添加Python路径。例如:“ C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python37 \ Lib \ site-packages”
  3. 单击“同步…”以允许其他程序(例如Jupyter Notebook)使用在步骤2中设置的pythonpaths。
  4. 如果Jupyter已打开,请重新启动

Solution without scripting:

  1. Open Spyder -> Tools -> PYTHONPATH manager
  2. Add Python paths by clicking “Add Path”. E.g: ‘C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages’
  3. Click “Synchronize…” to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  4. Restart Jupyter if it is open

回答 12

这可能是由系统上安装的不同python版本(即python2python3)引起的

运行命令$ pip --version$ pip3 --version检查哪个来自Python 3x。例如,您应该看到如下版本信息:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

然后example.py使用以下命令运行脚本

$ python3 example.py

This is probably caused by different python versions installed on your system, i.e. python2 or python3.

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Then run the example.py script with below command

$ python3 example.py

回答 13

出现在我的目录下utils。我试图将此目录导入为:

from utils import somefile

utils已经是python中的软件包。只需将您的目录名称更改为其他名称,它就可以正常工作。

Happened to me with the directory utils. I was trying to import this directory as:

from utils import somefile

utils is already a package in python. Just change your directory name to something different and it should work just fine.


回答 14

此类错误最有可能是由于python版本冲突引起的。例如,如果您的应用程序仅在python 3上运行,并且您还获得了python 2,那么最好指定要使用的版本。例如使用

python3 .....

代替

python

This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it’s better to specify which version to use. For example use

python3 .....

instead of

python

回答 15

该答案适用于此问题,如果

  1. 您不想更改代码
  2. 您不想永久更改PYTHONPATH

临时修改PYTHONPATH

下面的路径可以是相对的

PYTHONPATH=/path/to/dir python script.py

This answer applies to this question if

  1. You don’t want to change your code
  2. You don’t want to change PYTHONPATH permanently

Temporarily modify PYTHONPATH

path below can be relative

PYTHONPATH=/path/to/dir python script.py

回答 16

导入sys sys.path.append(’/ Users / {user} /Library/Python/3.7/lib/python/site-packages’)import ta

import sys sys.path.append(‘/Users/{user}/Library/Python/3.7/lib/python/site-packages’) import ta


回答 17

删除pathlib并重新安装它。删除sitepackages文件夹中的pathlib并使用pip命令重新安装pathlib软件包:

pip install pathlib

Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

pip install pathlib

将图像插入IPython Notebook Markdown

问题:将图像插入IPython Notebook Markdown

我开始严重依赖IPython Notebook应用程序来开发和记录算法。太棒了; 但是似乎有些应该可行的方法,但是我不知道该怎么做:

我想在我的(本地)IPython笔记本降价中插入本地图像,以帮助记录算法。我知道足够<img src="image.png">在降价中添加类似内容,但据我所知。我假设我可以将图像放在127.0.0.1:8888表示的目录(或某些子目录)中,以便能够访问它,但是我不知道该目录在哪里。(我正在Mac上工作。)那么,是否可以在没有太多麻烦的情况下做我想做的事情?

I am starting to depend heavily on the IPython notebook app to develop and document algorithms. It is awesome; but there is something that seems like it should be possible, but I can’t figure out how to do it:

I would like to insert a local image into my (local) IPython notebook markdown to aid in documenting an algorithm. I know enough to add something like <img src="image.png"> to the markdown, but that is about as far as my knowledge goes. I assume I could put the image in the directory represented by 127.0.0.1:8888 (or some subdirectory) to be able to access it, but I can’t figure out where that directory is. (I’m working on a mac.) So, is it possible to do what I’m trying to do without too much trouble?


回答 0

笔记本目录中的文件位于“ files /” URL下。因此,如果它位于基本路径中,则为<img src="files/image.png">,子目录等也可用:<img src="files/subdir/image.png">,等等。

更新:从IPython 2.0开始,files/不再需要该前缀(请参阅发行说明)。因此,现在该解决方案<img src="image.png">可以按预期工作。

Files inside the notebook dir are available under a “files/” url. So if it’s in the base path, it would be <img src="files/image.png">, and subdirs etc. are also available: <img src="files/subdir/image.png">, etc.

Update: starting with IPython 2.0, the files/ prefix is no longer needed (cf. release notes). So now the solution <img src="image.png"> simply works as expected.


回答 1

到目前为止,大多数给出的答案都是错误的,建议加载其他库并使用代码而不是标记。在Ipython / Jupyter Notebooks中,这非常简单。确保单元格确实在标记中并显示图像以供使用:

![alt text](imagename.png "Title")

与建议的其他方法相比,进一步的优点是您可以显示所有常见的文件格式,包括jpg,png和gif(动画)。

Most of the answers given so far go in the wrong direction, suggesting to load additional libraries and use the code instead of markup. In Ipython/Jupyter Notebooks it is very simple. Make sure the cell is indeed in markup and to display a image use:

![alt text](imagename.png "Title")

Further advantage compared to the other methods proposed is that you can display all common file formats including jpg, png, and gif (animations).


回答 2

我正在使用ipython 2.0,所以只有两行。

from IPython.display import Image
Image(filename='output1.png')

I am using ipython 2.0, so just two line.

from IPython.display import Image
Image(filename='output1.png')

回答 3

[过时]

IPython / Jupyter现在支持扩展模块,该模块可以通过复制和粘贴或拖放来插入图像。

https://github.com/ipython-contrib/IPython-notebook-extensions

拖放扩展似乎可以在大多数浏览器中使用

https://github.com/ipython-contrib/IPython-notebook-extensions/tree/master/nbextensions/usability/dragdrop

但是复制和粘贴仅适用于Chrome。

[Obsolete]

IPython/Jupyter now has support for an extension modules that can insert images via copy and paste or drag & drop.

https://github.com/ipython-contrib/IPython-notebook-extensions

The drag & drop extension seems to work in most browsers

https://github.com/ipython-contrib/IPython-notebook-extensions/tree/master/nbextensions/usability/dragdrop

But copy and paste only works in Chrome.


回答 4

将图像导入Jupyter NB比大多数人在这里提到的要简单得多。

1)只需创建一个空的Markdown单元。2)然后将图像文件拖放到空白的Markdown单元格中。

然后出现将插入图像的降价代码。

例如,下面以灰色突出显示的字符串将出现在Jupyter单元格中:

![Venus_flytrap_taxonomy.jpg](attachment:Venus_flytrap_taxonomy.jpg)

3)然后按Shift-Enter执行Markdown单元。然后,Jupyter服务器将插入图像,然后图像将出现。

我正在运行Jupyter笔记本服务器是:Windows 7上具有Python 3.7.0的5.7.4。

这是如此简单!

Getting an image into Jupyter NB is a much simpler operation than most people have alluded to here.

1) Simply create an empty Markdown cell. 2) Then drag-and-drop the image file into the empty Markdown cell.

The Markdown code that will insert the image then appears.

For example, a string shown highlighted in gray below will appear in the Jupyter cell:

![Venus_flytrap_taxonomy.jpg](attachment:Venus_flytrap_taxonomy.jpg)

3) Then execute the Markdown cell by hitting Shift-Enter. The Jupyter server will then insert the image, and the image will then appear.

I am running Jupyter notebook server is: 5.7.4 with Python 3.7.0 on Windows 7.

This is so simple !!


回答 5

我将IPython笔记本与图像放在同一文件夹中。我使用Windows。图像名称是“ phuong huong xac dinh.PNG”。

在Markdown中:

<img src="phuong huong xac dinh.PNG">

码:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

I put the IPython notebook in the same folder with the image. I use Windows. The image name is “phuong huong xac dinh.PNG”.

In Markdown:

<img src="phuong huong xac dinh.PNG">

Code:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

回答 6

首先确保您在ipython笔记本单元格中处于markdown编辑模型中

这是其他人提出的方法的替代方法<img src="myimage.png">

![title](img/picture.png)

如果标题丢失,它似乎也可以工作:

![](img/picture.png)

请注意,路径中不应包含任何引号。不知道这是否适用于带有空格的路径!

First make sure you are in markdown edit model in the ipython notebook cell

This is an alternative way to the method proposed by others <img src="myimage.png">:

![title](img/picture.png)

It also seems to work if the title is missing:

![](img/picture.png)

Note no quotations should be in the path. Not sure if this works for paths with white spaces though!


回答 7

Jupyter Notebook的最新版本本机接受图像的复制/粘贴

Last version of jupyter notebook accepts copy/paste of image natively


回答 8

如果要在Markdown单元中显示图像,请使用:

<img src="files/image.png" width="800" height="400">

如果要在“代码”单元格中显示图像,请使用:

from IPython.display import Image
Image(filename='output1.png',width=800, height=400)

If you want to display the image in a Markdown cell then use:

<img src="files/image.png" width="800" height="400">

If you want to display the image in a Code cell then use:

from IPython.display import Image
Image(filename='output1.png',width=800, height=400)

回答 9

在运行此代码之前,将默认块从“代码”更改为“ Markdown”:

![<caption>](image_filename.png)

如果图像文件在另一个文件夹中,则可以执行以下操作:

![<caption>](folder/image_filename.png)

Change the default block from “Code” to “Markdown” before running this code:

![<caption>](image_filename.png)

If image file is in another folder, you can do the following:

![<caption>](folder/image_filename.png)

回答 10

对于那些希望将图像文件放在Jupyter机器上的位置的人,以便可以从本地文件系统显示它。

我把我的mypic.png

/root/Images/mypic.png

(即Jupyter在线文件浏览器中显示的Images文件夹)

在这种情况下,我需要将以下行放入Markdown单元中,以使我的图片显示在记事本中:

![My Title](Images/mypic.png)

For those looking where to place the image file on the Jupyter machine so that it could be shown from the local file system.

I put my mypic.png into

/root/Images/mypic.png

(that is the Images folder that shows up in the Jupyter online file browser)

In that case I need to put the following line into the Markdown cell to make my pic showing in the notepad:

![My Title](Images/mypic.png)

回答 11

明克的答案是正确的。

但是,我发现这些图像在“打印视图”中显得不完整(在运行Chrome浏览器中IPython 0.13.2版的Anaconda发行版的Windows计算机上)

解决方法是使用 <img src="../files/image.png">

这使得图像可以在“打印视图”和普通的iPython编辑视图中正确显示。

更新:自从我升级到iPython v1.1.0以来,由于打印视图不再存在,因此不再需要这种解决方法。实际上,您必须避免这种解决方法,因为它会阻止nbconvert工具查找文件。

minrk’s answer is right.

However, I found that the images appeared broken in Print View (on my Windows machine running the Anaconda distribution of IPython version 0.13.2 in a Chrome browser)

The workaround for this was to use <img src="../files/image.png"> instead.

This made the image appear correctly in both Print View and the normal iPython editing view.

UPDATE: as of my upgrade to iPython v1.1.0 there is no more need for this workaround since the print view no longer exists. In fact, you must avoid this workaround since it prevents the nbconvert tool from finding the files.


回答 12

您可以在jupyter笔记本中使用“ pwd”命令查找当前工作目录,不带引号。

You can find your current working directory by ‘pwd’ command in jupyter notebook without quotes.


如何在Jupyter Notebook中显示文件中的图像?

问题:如何在Jupyter Notebook中显示文件中的图像?

我想使用IPython笔记本作为交互式分析我使用Biopython GenomeDiagram模块制作的一些基因组图的方法。尽管有大量有关如何matplotlib在IPython笔记本中用于内联获取图形的文档,但GenomeDiagram使用ReportLab工具箱,我认为IPython不支持内联图形。

但是,我当时想,一种解决方法是将绘图/基因组图写到文件中,然后打开图像内联图像,结果将是相同的,如下所示:

gd_diagram.write("test.png", "PNG")
display(file="test.png")

但是,我不知道该怎么做-或知道是否可能。有人知道是否可以在IPython中打开/显示图像吗?

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython’s GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don’t think is supported for inline graphing in IPython.

I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:

gd_diagram.write("test.png", "PNG")
display(file="test.png")

However, I can’t figure out how to do this – or know if it’s possible. So does anyone know if images can be opened/displayed in IPython?


回答 0

通过此帖子,您可以执行以下操作:

from IPython.display import Image
Image(filename='test.png') 

官方文档

Courtesy of this post, you can do the following:

from IPython.display import Image
Image(filename='test.png') 

(official docs)


回答 1

如果试图在循环中以这种方式显示Image,则需要将Image构造函数包装在display方法中。

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))

If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))

回答 2

请注意,到目前为止发布的解决方案仅适用于png和jpg!

如果您希望它更容易而不导入其他库,或者要在Ipython Notebook中显示动画或不动画的GIF文件。将您要显示的行转换为降价标记,并使用此简短的技巧!

![alt text](test.gif "Title")

Note, until now posted solutions only work for png and jpg!

If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!

![alt text](test.gif "Title")

回答 3

这将.jpg在Jupyter中导入并显示图像(在Anaconda环境中使用Python 2.7测试)

from IPython.display import display
from PIL import Image


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

您可能需要安装PIL

在Anaconda中,这是通过键入

conda install pillow

This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)

from IPython.display import display
from PIL import Image


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

You may need to install PIL

in Anaconda this is done by typing

conda install pillow

回答 4

感谢页面,当以上建议不起作用时,我发现此方法有效:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

Courtesy of this page, I found this worked when the suggestions above didn’t:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

回答 5

您可以在markdown部分的html代码中使用:示例:

 <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />

You could use in html code in markdown section: example:

 <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />

回答 6

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

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

pil_im = Image.open('image.png') #Take jpg + png
## 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.png') #Take jpg + png
## 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()

回答 7

如果要有效显示大量图像,建议使用IPyPlot软件包

import ipyplot

ipyplot.plot_images(images_array, max_images=20, img_width=150)

该软件包中还有一些其他有用的功能,您可以在其中以交互式选项卡(每个标签/类别的单独选项卡)显示图像,这对于所有ML分类任务都非常有用。

If you want to efficiently display big number of images I recommend using IPyPlot package

import ipyplot

ipyplot.plot_images(images_array, max_images=20, img_width=150)

There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.


回答 8

GenomeDiagram与Jupyter(iPython)一起使用时,显示图像的最简单方法是将GenomeDiagram转换为PNG图像。可以使用IPython.display.Image对象包装它,使其在笔记本中显示。

from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))

[请参阅笔记本]

When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.

from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))

[See Notebook]