Chr*_*oph 66 python ipython ipython-notebook
我有一些Python代码示例我想分享,如果在终端Python/IPython或IPython笔记本中执行,应该做一些不同的事情.
如何从我的Python代码中检查它是否在IPython笔记本中运行?
kef*_*ich 40
要检查您是否在笔记本中,这可能很重要,例如在确定使用哪种进度条时,这对我有用:
def in_ipynb():
try:
cfg = get_ipython().config
if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':
return True
else:
return False
except NameError:
return False
Run Code Online (Sandbox Code Playgroud)
Gus*_*rra 39
以下是我的需求:
get_ipython().__class__.__name__
Run Code Online (Sandbox Code Playgroud)
它'TerminalInteractiveShell'在终端IPython 'ZMQInteractiveShell'上返回,在Jupyter(笔记本和qtconsole)上返回,并NameError在常规Python解释器上失败().get_python()默认情况下,启动IPython时,该方法似乎在全局命名空间中可用.
将其包装在一个简单的功能中:
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
Run Code Online (Sandbox Code Playgroud)
在MacOS 10.12和Ubuntu 14.04.4 LTS上使用Python 3.5.2,IPython 5.1.0和Jupyter 4.2.1测试了上述内容
Til*_*ann 21
您可以使用以下代码段[1]检查python是否处于交互模式:
def is_interactive():
import __main__ as main
return not hasattr(main, '__file__')
Run Code Online (Sandbox Code Playgroud)
我发现这种方法非常有用,因为我在笔记本中进行了大量的原型设计.出于测试目的,我使用默认参数.否则,我从中读取参数sys.argv.
from sys import argv
if is_interactive():
params = [<list of default parameters>]
else:
params = argv[1:]
Run Code Online (Sandbox Code Playgroud)
dee*_*nes 13
最近我在Jupyter笔记本中遇到了一个需要解决方法的错误,我希望这样做而不会丢失其他shell中的功能.我意识到keflavich的解决方案在这种情况下不起作用,因为get_ipython()它只能直接从笔记本电脑上获得,而不能从导入的模块中获得.所以我找到了一种从我的模块中检测它是否从Jupyter笔记本导入和使用的方法:
import sys
def in_notebook():
"""
Returns ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
return 'ipykernel' in sys.modules
# later I found out this:
def ipython_info():
ip = False
if 'ipykernel' in sys.modules:
ip = 'notebook'
elif 'IPython' in sys.modules:
ip = 'terminal'
return ip
Run Code Online (Sandbox Code Playgroud)
如果足够强大,则表示赞赏.
类似的方式可以获得有关客户端和IPython版本的一些信息:
import sys
if 'ipykernel' in sys.modules:
ip = sys.modules['ipykernel']
ip_version = ip.version_info
ip_client = ip.write_connection_file.__module__.split('.')[0]
# and this might be useful too:
ip_version = IPython.utils.sysinfo.get_sys_info()['ipython_version']
Run Code Online (Sandbox Code Playgroud)
Rob*_*wak 13
针对 python 3.7.3 进行了测试
CPython 实现的名称可__builtins__作为其全局变量的一部分,顺便说一句。可以通过函数 globals() 检索。
如果脚本在 Ipython 环境中运行,那么__IPYTHON__应该是__builtins__.
因此,如果在 Ipython 下运行,下面的代码将返回True,否则它给出False
hasattr(__builtins__,'__IPYTHON__')
Run Code Online (Sandbox Code Playgroud)
问题是你想要以不同的方式执行什么.
我们在IPython中尽力而为,防止内核知道连接的是哪种前端,实际上你甚至可以同时将内核连接到许多不同的前端.即使您可以看一下stderr/out您是否知道ZMQ内核中的类型,但它并不能保证您在另一方面拥有的内容.你甚至可以没有前端.
您应该以独立于前端的方式编写代码,但是如果要显示不同的内容,可以使用富显示系统(链接到IPython的4.x版本)根据前端显示不同的内容,但是前端会选择,而不是图书馆.