Третий (36-минутный)видеоролик начинается с рекомендаций по получению помощи (help), далее излагаются принципы работы с конфигурационными файлами, создается дополнительный профиль, разбираются команды консоли и %config magic ...приводится пример с построением синусоиды с Numpy и перенастройкой формата вывода картинки "%config InlineBackend.figure_format = 'svg'". Затем рассматривается пример "Start Up files"
Finding configuration options¶
IPython has many configurable attributes. These can be viewed using the
-h
flag to the command line applications:
In [1]:
!ipython -h
This is an important trick for finding out configuration info:
$> ipython [subcommand] --help-all | grep [-C context] PATTERN
--help-all
exposes everything configurable in IPython, there is a good chance you will find what you are looking for.
A common configuration question is:
how do I disable the "Do you really want to exit" message when quitting with Ctrl-d
?
Well, logically this has to do with exit
, so let's look for it:
In [2]:
!ipython --help-all | GREP_COLOR='1;31;46' grep --color exit
Which shows me that I can disable the confirmation for a single IPython session with
$> ipython --no-confirm-exit
or I can set the TerminalInteractiveShell.confirm_exit=False
in a config file, to have it be the default behavior.
на скорую руку для Windows без цвета это можно выполнить так:
In [3]:
!chcp 65001
!ipython --help-all | find "exit"
Configuration principles¶
Here are the design principles of the IPython configuration system:
- Configuration is always done using class attributes
- Classes that have configurable attributes are subclasses of
Configurable
- Attributes that are configurable are typed traitlets objects (
Bool
,Unicode
, etc.) that haveconfig=True
- In config files, configurable attributes can be set using the format
Class.attr_name=the_value
- At the command line, configurable attributes can be set using the syntax
--Class.attr_name=the_value
- At the command line, some attributes have shorthands of the form
--attr-name=value
- Values set at the command line have higher priority than those set in config files
The IPython Profile¶
IPython has a notion of 'profiles' - these are directories that live in your IPYTHONDIR, which contain configuration and runtime information.
Let's create the default profile
Let's create the default profile
In [3]:
!ipython profile create newprofile
This creates a profile in your IPYTHONDIR (
ipython locate
is a quick way to see where your IPYTHONDIR is), and populates it with automatically generated default config files.
In [4]:
!ipython locate profile default
!ipython locate profile newprofile
Для Windows путь немного другой... стоит отметить, что эта команда еще и "populates it with automatically generated default config files"
In [4]:
!ipython locate profile default
You can skim
In [5]:
profile = get_ipython().profile_dir.location
profile
Out[5]:
In [6]:
ls $profile
In [5]:
profile = get_ipython().profile_dir.location
profile
Out[5]:
In [6]:
ls $profile
Let's peek at our config file
In [7]:
pycat $profile/ipython_config.py
В моей profile директории нет файла ipython_config.py Наверное, это от того, что я не создал еще один профиль... Но там (C:\Users\kiss\.ipython) я нашел "readme", в котором была вот эта ссылка на хелпер:
In [8]:
!ipython config -h
The %config magic¶
The
%config
magic lets you do some configuration at runtime, rather than in configuration files.
In [10]:
%matplotlib inline
%config
with no arguments will show you what configurable objects exist:
In [9]:
%config
In [11]:
%config InlineBackend
Последняя строчка " InlineBackend" появляется после выполнения команды "%matplotlib inline"... А остальные классы-конфигуоаторы как идентифицировать?
And
%config Class
will show you the config for that class:
In [10]:
%config InlineBackend
Most importantly, the
%config
magic can be used to change the value of a configurable attribute at runtime. Here we tell the inline matplotlib backend to use SVG instead of the default PNG
In [11]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,1000)
y = np.sin(x)
plt.plot(x,y)
Out[11]:
In [12]:
%config InlineBackend.figure_format = 'svg'
In [13]:
plt.plot(x,y)
Out[13]:
Startup Files¶
Startup files are simple Python or IPython scripts that are run whenever you start IPython. These are a useful way to do super common imports, or for building database connections to load on startup of a non-default profile.
We can use a startup file to ensure that our
We can use a startup file to ensure that our
%tic/toc
magics are always defined, every time we start IPython.
In [14]:
!ls $profile/startup
Для Windows работает и "dir" и "ls", надо только слэш поменять на обратный для dir
In [14]:
!dir $profile\startup
In [15]:
!cat $profile/startup/README
*Выше встречалась команда "pycat
In [17]:
# вместо !cat $profile/startup/README
pycat $profile/startup/README
Для Windows... Слэш обратный !!! Иначе ошибка !!!
In [24]:
!type $profile\startup\README
Adding common imports, so we never have to forget them again
In [16]:
%%writefile $profile/startup/simpleimports.py
import sys, os, time, re
Restart the kernel and then run the following cells immediately to verify these scripts have been executed:
In [1]:
sys
Out[1]:
Extensions¶
In [2]:
profile = get_ipython().profile_dir.location
In [3]:
!cat $profile/ipython_config.py | grep InteractiveShellApp.extensions
In [4]:
!echo "c.InteractiveShellApp.extensions = ['mymagics']" >> $profile/ipython_config.py
!tail $profile/ipython_config.py
Restart the kernel to see the effects:
In [1]:
import time
%tic
time.sleep(0.1)
%toc
In [2]:
%nbrun Sample
Посты чуть ниже также могут вас заинтересовать
Комментариев нет:
Отправить комментарий