如何检查代码是否在IPython笔记本中执行? [英] How can I check if code is executed in the IPython notebook?

查看:199
本文介绍了如何检查代码是否在IPython笔记本中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些Python代码示例我想分享,如果在终端Python / IPython或IPython笔记本中执行,应该做一些不同的事情。

I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.

如何我可以从我的Python代码中检查它是否在IPython笔记本中运行吗?

How can I check from my Python code if it's running in the IPython notebook?

推荐答案

问题是你想要以不同的方式执行什么。

The question is what do you want execute differently.

我们在IPython中尽我所能阻止内核知道连接的是哪种前端,实际上你甚至可以在同一个前端连接许多不同的前端时间。即使你可以看一下 stderr / out 的类型,知道你是否在ZMQ内核中,它也不能保证你拥有的内容。另一边。你甚至可以没有前端。

We do our best in IPython prevent the kernel from knowing to which kind of frontend is connected, and actually you can even have a kernel connected to many differents frontends at the same time. Even if you can take a peek at the type of stderr/out to know wether you are in a ZMQ kernel or not, it does not guaranties you of what you have on the other side. You could even have no frontends at all.

您应该以独立于前端的方式编写代码,但如果要显示不同的东西,可以使用< a href =http://nbviewer.jupyter.org/github/ipython/ipython/blob/4.x/examples/IPython%20Kernel/Rich%20Output.ipynb\"rel =nofollow noreferrer>丰富的显示系统(链接)固定到IPy的4.x版本)根据前端显示不同的东西,但前端会选择,而不是库。

You should probably write your code in a frontend independent manner, but if you want to display different things, you can use the rich display system (link pinned to version 4.x of IPython) to display different things depending on the frontend, but the frontend will choose, not the library.

这篇关于如何检查代码是否在IPython笔记本中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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