Jupyter QtConsole 配置,2023 年了你还在使用 QtConsole 吗?

Jupyter QtConsole 配置,2023 年了你还在使用 QtConsole 吗?

Jupyter 想必大家已经很熟悉了,它是一个开源的交互式计算环境,支持多种编程语言。它提供了一个灵活的界面,可以在浏览器中创建和共享包含代码、文本和图像的笔记本。

其实在 Jupyter Notebook 和 JupyterLab 之外还有一个 Jupyter QtConsole,和 IPython Shell 一样,是实时的交互式终端。只不过由于是在 Qt 窗口中显示,所以可以实时渲染代码的结果、可视化等。

有的时候我们并不打算完成一个完整的任务,而只是要运行一些简单的代码。在这种情况下我们就可以使用 Jupyter QtConsole 来帮助我们完成任务。

Jupyter QtConsole 的安装

理论上用 pip 安装完 Jupyter 之后就可以直接使用 jupyter qtconsole 命令运行了。但是这个时候可能会报错。这是因为 Jupyter QtConsole 依赖 PyQt5。

pip install PyQt5

安装完成后就可以愉快地使用了。

设置字体

跟 Jupyter Notebook 一样,首先在命令行中运行以下命令来生成配置文件:

jupyter qtconsole --generate-config

这将在默认位置创建一个名为 jupyter_qtconsole_config.py 的配置文件,一般在用户的主目录(Windows 下的 C:\Users\[你的用户名]),也就是 ~ 下有一个 .jupyter 文件夹。配置文件默认生成在这里。

使用任何文本编辑器(vim,nano,Visual Stdio Code,Subline Text,Atom 或者为微软记事本之类的)打开 jupyter_qtconsole_config.py 文件。

找到以下两行并进行编辑:

c.ConsoleWidget.font_family = 'Consolas'
c.ConsoleWidget.font_size = 12

你可以根据自己的喜好来选择合适的字体和大小。确保使用引号将字体名称括起来,并且注意缩进。

保存修改后的配置文件,返回到命令行,重新启动 Jupyter QtConsole 并应用你的新配置:

jupyter qtconsole

现在,你应该能看到字体已经改变了。

启动时自动加载需要的库包

首先进入到 IPython 的配置文件的目录,具体路径因设置而异。没设置过则默认在 C:\Users\[你的用户名]\.ipython。路径下面有文件夹 \profile_default\startup,里面有个 README 文件:

This is the IPython startup directory

.py and .ipy files in this directory will be run *prior* to any code or files specified
via the exec_lines or exec_files configurables whenever you load this profile.

Files will be run in lexicographical order, so you can control the execution order of files
with a prefix, e.g.::

    00-first.py
    50-middle.py
    99-last.ipy

大概的意思就是说在这个目录下面添加 .py 或者 .ipy文件,ipython 会首先执行里面的代码。

我们创建一个 00-autoload_libs.py,里面导入想要的库包:

print()
print('packages autoloading ...\n')
print('This may take a few seconds.\n')

# import Libs
import numpy as np
print('numpy --> np')
import pandas as pd
print('pandas --> pd')
import matplotlib.pyplot as plt
print('matplotlib.pyplot --> plt')

import networkx as nx
print('networkx --> nx')
import control as ctrl
print('control --> ctrl')

import seaborn as sns
print('seaborn --> sns')

import sympy as sp
print('sympy --> sp')

# set sympy printing display
sp.init_printing(use_latex='mathjax')

大功告成。现在每次 Jupyter Console 启动都会自动加载了。

不错,很好用。


更新:2023 年 10 月 24 日

好吧我后悔了。通过编辑 00-autoload_libs.py 导入库包的方法似乎会导致使用 Jupyter Notebook 的时候电脑变卡严重。具体原因未知。

新的解决方法:使用 pyforest,将 00-autoload_libs.py 改为:

import pyforest
print()
print('pyforest imported.')

如果没有安装过 pyforest,可以自行安装。

pip install pyforest

pyforest 库是一个用于支持惰性导入模块的库。简单的来说,你可以用简单的 import pyforest 代替 NumPy、Pandas、MatPlotLib 等诸多数据分析和数值计算的库包的导入的繁琐流程。在代码下文中调用 nppd 或者 plt 的时候,pyforest 会帮你您自动匹配;而如果没有调用这些模块,pyforest 则不会启用这些模块。这可以帮你减小电脑的内存占用。

posted @ 2023-10-22 16:55  多玩我的世界盒子  阅读(113)  评论(0编辑  收藏  举报