ipython:如何设置终端宽度
当我使用 ipython terminal
并想要打印一个有很多列的 numpy.ndarray
时,输出的行会自动在大约80个字符的地方换行(也就是说,行的宽度大约是80个字符)。
z = zeros((2,20))
print z
我猜 ipython
是认为我的终端宽度是80列。但实际上,我的终端宽度是176个字符,我想要充分利用这个宽度。
我尝试过更改以下参数,但没有任何效果:
c.PlainTextFormatter.max_width = 160
我该如何告诉 ipython
使用我终端的全部宽度呢?
我在 Debian Wheezy 上使用 ipython 1.2.1
4 个回答
使用这个方法:
np.set_printoptions(linewidth=300)
然后用这个来扩展你的ipython视图:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
为了在你调整窗口大小时,自动调整numpy和IPython的大小,可以把下面的内容添加到你的 ipython_config.py
文件中:
import IPython
import signal
import shutil
import sys
try:
import numpy as np
except ImportError:
pass
c = get_config()
def update_terminal_width(*ignored):
"""Resize the IPython and numpy printing width to match the terminal."""
w, h = shutil.get_terminal_size()
config = IPython.get_ipython().config
config.PlainTextFormatter.max_width = w - 1
shell = IPython.core.interactiveshell.InteractiveShell.instance()
shell.init_display_formatter()
if 'numpy' in sys.modules:
import numpy as np
np.set_printoptions(linewidth=w - 5)
# We need to configure IPython here differently because get_ipython() does not
# yet exist.
w, h = shutil.get_terminal_size()
c.PlainTextFormatter.max_width = w - 1
if 'numpy' in sys.modules:
import numpy as np
np.set_printoptions(linewidth=w - 5)
signal.signal(signal.SIGWINCH, update_terminal_width)
如果你想等到需要的时候再加载numpy,可以查看 Python 3中的导入钩子,那里有解决方案。
如果你不使用IPython,可以把上面的内容放到你的PYTHONSTARTUP文件里,并去掉与IPython相关的部分。
你可以通过以下方式查看当前的行宽:
numpy.get_printoptions()['linewidth']
并且可以用下面的方式来设置它:
numpy.set_printoptions(linewidth=160)
自动设置打印宽度
如果你想让终端的宽度自动设置,可以让Python执行一个启动脚本。所以,创建一个文件 ~/.python_startup.py
,或者你想叫的其他名字,在里面写上以下内容:
# Set the printing width to the current terminal width for NumPy.
#
# Note: if you change the terminal's width after starting Python,
# it will not update the printing width.
from os import getenv
terminal_width = getenv('COLUMNS')
try:
terminal_width = int(terminal_width)
except (ValueError, TypeError):
print('Sorry, I was unable to read your COLUMNS environment variable')
terminal_width = None
if terminal_width is not None and terminal_width > 0:
from numpy import set_printoptions
set_printoptions(linewidth = terminal_width)
del terminal_width
为了让Python每次都执行这个脚本,打开你的 ~/.bashrc
文件,然后添加:
# Instruct Python to execute a start up script
export PYTHONSTARTUP=$HOME/.python_startup.py
# Ensure that the startup script will be able to access COLUMNS
export COLUMNS
经过一番查找代码后,发现你要找的变量是 numpy.core.arrayprint._line_width
,默认值是75。把它设置成160对我来说是有效的:
>>> numpy.zeros((2, 20))
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
默认情况下,用于数组格式化的函数是 numpy.core.numeric.array_repr
,不过你可以用 numpy.core.numeric.set_string_function
来更改这个函数。