Здесь (2) продолжение видео "IPython in Depth, SciPy2013 Tutorial, Part 2 of 3" (до 46 минуты). Пример работы с %load, загружаем скрипт с [matplotlib.org] (http://matplotlib.org/examples/api/histogram_path_demo.html) и выполняем его получаем гистограмму в отдельном окне редктора
First and foremost, the IPython Notebook is an interactive environment for writing and running Python code.
Code cells allow you to enter and run Python code¶
Run a code cell using
Shift-Enter
or pressing the "Play" button in the toolbar above:
In [1]:
a = 10
In [2]:
print(a)
You can run a cell in place using
Ctrl-Enter
:
In [7]:
pwd
Out[7]:
Managing the IPython Kernel¶
Code is run in a separate process called the IPython Kernel. The Kernel can be interrupted or restarted. Try running the following cell and then hit the "Stop" button in the toolbar above.
In [4]:
import time
time.sleep(10)
If the Kernel dies you will be prompted to restart it. Here we call the low-level system libc.time routine with the wrong argument via ctypes to segfault the Python interpreter:
In [1]:
import sys
from ctypes import CDLL
# This will crash a Linux or Mac system; equivalent calls can be made on Windows
dll = 'dylib' if sys.platform == 'darwin' else 'so.6'
libc = CDLL("libc.%s" % dll)
libc.time(-1) # BOOM!!
Exercise¶
Define a variable in a Notebook, then use the "Kernel:Restart" menu item to restart the Kernel and verify that the variable has been cleared.
Working with external code¶
There are a number of ways of getting external code into code cells.
Pasting code with
>>>
prompts works as expected:
In []:
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
The
%load
magic lets you load code from URLs or local files:
In [2]:
%load?
Type: Magic function String Form:> Namespace: IPython internal File: c:-packages.py Definition: %load(self, arg_s) Docstring: Load code into the current frontend.
Usage: %load [options] source
where source can be a filename, URL, input history range or macro
This magic command can either take a local filename, a URL, an history range (see %history) or a macro as argument, it will prompt for confirmation before loading source with more than 200 000 characters, unless -y flag is passed or if the frontend does not support raw_input::
%load myscript.py %load 7-27 %load myMacro %load http://www.example.com/myscript.py
Usage: %load [options] source
where source can be a filename, URL, input history range or macro
Options:
-y : Don't ask confirmation for loading source above 200 000 characters.This magic command can either take a local filename, a URL, an history range (see %history) or a macro as argument, it will prompt for confirmation before loading source with more than 200 000 characters, unless -y flag is passed or if the frontend does not support raw_input::
%load myscript.py %load 7-27 %load myMacro %load http://www.example.com/myscript.py
Exercise¶
Go to the Matplotlib gallery, view the raw Python code for an example, use
%load
to load it into a cell and then run it. Make sure you run:%pylab inline
first to enable plotting support.
In []:
%load soln/load.py
In [3]:
%load http://matplotlib.org/mpl_examples/api/histogram_path_demo.py
In [9]:
"""
This example shows how to use a path patch to draw a bunch of
rectangles. The technique of using lots of Rectangle instances, or
the faster method of using PolyCollections, were implemented before we
had proper paths with moveto/lineto, closepoly etc in mpl. Now that
we have them, we can draw collections of regularly shaped objects with
homogeous properties more efficiently with a PathCollection. This
example makes a histogram -- its more work to set up the vertex arrays
at the outset, but it should be much faster for large numbers of
objects
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
fig, ax = plt.subplots()
# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 50)
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left,left,right,right], [bottom,top,top,bottom]]).T
# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)
# make a patch out of it
patch = patches.PathPatch(barpath, facecolor='blue', edgecolor='gray', alpha=0.8)
ax.add_patch(patch)
# update the view limits
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
plt.show()
In [8]:
%matplotlib inline
Выше картинка Сначала я запустил скрипт наверху без команды внизу "%matplotlib inline" и гистограмма отркрылась в отдельном окне редактора, так что, надо запомнить эту команду... ниже тег изображения с использованием data:image/png
In []:
<img src="data:image/png;base64, iVBOR....... ... ......CYII="
class="ui-resizable" style="margin: 0px; resize: none; position: static; zoom: 1; display: block; height: 351px; width: 499px;">
Run all¶
It is also possible to run all cells in a Notebook by using the "Cell" menu its "Run All".
Посты чуть ниже также могут вас заинтересовать
Комментариев нет:
Отправить комментарий