Python an sich ist ein Interpreter für die Programmiersprache Python mit einer sehr umfangreichen Programmierbibliothek.
IPython ist ein *i*nteraktives System um mit einer laufenden Pythoninstanz arbeiten zu können. Dieses hier vorliegende Skriptum ist eine Sammlung sogenannter "IPython Notebooks". Diese sind jeweils interaktive Dokumente, welche aus Text, Code, und Codergebnissen bestehen. Daher ist es möglich, dieses gesamte Skriptum herunterzuladen und in IPython auszuführen. Jede Codezelle kann nicht nur lokal ausgeführt werden, sondern läd auch zum interaktiven Experimentieren ein.
$ ipython notebook
in der Kommandozeile in einem vorher gewählten Verzeichnis.
Es öffnet sich dann der standardmäßig eingestellte Web-browser für das grafische Interface (engl. GUI).
Möchte man den Browser explizit festlegen, so geschieht dies über die Umgebungsvariable BROWSER
:
$ BROWSER=firefox ipython notebook
bzw. das Öffnen eines Browserfensters kann so verhindert werden:
$ ipython notebook --no-browser
Ein geöffnetes Notebook speichert sich periodisch ab, jedoch ist empfehlenswert dies regelmäßig mittels bzw. durchzuführen. File
→ Save and Checkpoint
speichert darüber hinaus einen Checkpoint ab. Dadurch lässt sich zu einer früheren Version zurückspringen. Für eine genauere Versionskontrolle bzw. Gruppenkollaborationen ist Git empfehlenswert.
Der Notebook Server muss nach getaner Arbeit beendet werden. Dazu 2x im Terminal betätigen.
also insbesondere weder deren Position noch deren Existenz!
Grundsätzlich unterscheidet man dabei zwei Bedienmodalidäten: Editermodus und Kommandomodus. Im Editiermodus kann man den Inhalt der aktiven Zelle verändern, während im Kommandomus Befehle an das gesamte Notebook geschickt werden, die aktive Zelle gewählt werden kann, etc.
Ein Mausklick auf eine Zelle wählt sie aktiv aus, ein Doppelklick oder und man kann sie editieren. Zurück in den Kommandomodous kommt man mit (ohne Auswertung) bzw. + (mit Auswertung).
Die folgenden Tastenkombinationen sind sehr praktisch, und für eine effektive Bedienung unerlässlich.
Kommandomodus: Dieser Modus erlaubt zwischen den Zellen herumzuspringen, Zellen zu löschen, kopieren, verschieben, etc.
Editiermodus: Diese dient der Bearbeitung des Inhalts einer ausgewählten Zelle
Definiere die Variable donaudampfschiffahrtsgesellschaft
, und anschließend tippe donaud[TAB]
und beachte, was passiert.
donaudampfschiffahrtsgesellschaft = 1
donaud
NameErrorTraceback (most recent call last) <ipython-input-2-c2f4bbd70b03> in <module>() ----> 1 donaud NameError: name 'donaud' is not defined
Dies ist insbesondere für objektorientie Programmierung interessant, da hier nach dem Objekt ("Subjekt"), durch einen Punkt getrennt, das Attribut ("Objekt") oder die Methode ("Verb") angeführt wird.
Beispiel: Methoden und Attribute einer Liste:
l = ["Affe", "Hund", "Katze"]
l.
File "<ipython-input-2-37cab99ee337>", line 1 l. ^ SyntaxError: invalid syntax
Ist l
definiert, liefert ein Druck auf die Tabulatortaste wenn der Cursor gleich nach l.
steht, dies:
from IPython.display import Image
from os.path import join
Image(filename = join("res", "ipython-tabcompletion.png"))
Entweder mit help(...)
oder mit nachgestelltem ?
.
zu einem Befehl
help(list)
zu einer Objektinstanz, mittels der jeweiligen Variablen
l = [2, 3]
l?
zu einer Methode einer Objektinstanz
l.reverse?
oder
help(l.count)
Help on built-in function count: count(...) method of builtins.list instance L.count(value) -> integer -- return number of occurrences of value
zu einem ganzen Modul
import math
help(math)
Help on module math: NAME math MODULE REFERENCE http://docs.python.org/3.5/library/math The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. acosh(...) acosh(x) Return the inverse hyperbolic cosine of x. asin(...) asin(x) Return the arc sine (measured in radians) of x. asinh(...) asinh(x) Return the inverse hyperbolic sine of x. atan(...) atan(x) Return the arc tangent (measured in radians) of x. atan2(...) atan2(y, x) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. atanh(...) atanh(x) Return the inverse hyperbolic tangent of x. ceil(...) ceil(x) Return the ceiling of x as an int. This is the smallest integral value >= x. copysign(...) copysign(x, y) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. cos(...) cos(x) Return the cosine of x (measured in radians). cosh(...) cosh(x) Return the hyperbolic cosine of x. degrees(...) degrees(x) Convert angle x from radians to degrees. erf(...) erf(x) Error function at x. erfc(...) erfc(x) Complementary error function at x. exp(...) exp(x) Return e raised to the power of x. expm1(...) expm1(x) Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. fabs(...) fabs(x) Return the absolute value of the float x. factorial(...) factorial(x) -> Integral Find x!. Raise a ValueError if x is negative or non-integral. floor(...) floor(x) Return the floor of x as an int. This is the largest integral value <= x. fmod(...) fmod(x, y) Return fmod(x, y), according to platform C. x % y may differ. frexp(...) frexp(x) Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. fsum(...) fsum(iterable) Return an accurate floating point sum of values in the iterable. Assumes IEEE-754 floating point arithmetic. gamma(...) gamma(x) Gamma function at x. gcd(...) gcd(x, y) -> int greatest common divisor of x and y hypot(...) hypot(x, y) Return the Euclidean distance, sqrt(x*x + y*y). isclose(...) is_close(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool Determine whether two floating point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the magnitude of the input values abs_tol maximum difference for being considered "close", regardless of the magnitude of the input values Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves. isfinite(...) isfinite(x) -> bool Return True if x is neither an infinity nor a NaN, and False otherwise. isinf(...) isinf(x) -> bool Return True if x is a positive or negative infinity, and False otherwise. isnan(...) isnan(x) -> bool Return True if x is a NaN (not a number), and False otherwise. ldexp(...) ldexp(x, i) Return x * (2**i). lgamma(...) lgamma(x) Natural logarithm of absolute value of Gamma function at x. log(...) log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. log10(...) log10(x) Return the base 10 logarithm of x. log1p(...) log1p(x) Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. log2(...) log2(x) Return the base 2 logarithm of x. modf(...) modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. pow(...) pow(x, y) Return x**y (x to the power of y). radians(...) radians(x) Convert angle x from degrees to radians. sin(...) sin(x) Return the sine of x (measured in radians). sinh(...) sinh(x) Return the hyperbolic sine of x. sqrt(...) sqrt(x) Return the square root of x. tan(...) tan(x) Return the tangent of x (measured in radians). tanh(...) tanh(x) Return the hyperbolic tangent of x. trunc(...) trunc(x:Real) -> Integral Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 FILE /projects/anaconda3/lib/python3.5/lib-dynload/math.cpython-35m-x86_64-linux-gnu.so
Das Auswerten der Zellen, und insbesondere das zuweisen von Werten an Variablen, ändert den globalen Status.
Wie schon erwähnt, ist die Reihenfolge und der Code der jeweils ausgeführten Zellen relevant -- nicht deren Position oder Existenz.
Mit %whos
kann man sich eine Übersicht über alle aktuellen Variablenwerte verschaffen:
x = 42
y = 2 * x
%whos
Variable Type Data/Info -------------------------------- Image type <class 'IPython.core.display.Image'> join function <function join at 0x7f4158e332f0> l list n=2 math module <module 'math' from '/pro<...>35m-x86_64-linux-gnu.so'> x int 42 y int 84
Der -Button startet den Kernel neu und löscht damit alle Variablen und geladenen Module.
Nebst den Codezellen gibt es auch Zellen die Fließtext oder Überschriften beinhalten können. Dies lässt sich für die aktuell gewählte Zelle in dem Dropdownmenü neben dem Reload-Button einstellen.
Die Formatierung ist hierbei vereinfachtes Markdown,
also insbesondere Textauszeichnungen wie: *wort*
, _wort_
, **wort**
oder [link text](http://url/)
. Überschriften werden durch ein, zwei oder drei #
am Zeilenbeginn signalisiert.
Um Programmcode anzugeben, ohne dass er ausgeführt wird, setzt man ihn in Markdown-Zellen unter verkehrte einfache Anführungszeichen. Mehrzeiliger Code ist zwischen ```
einzufügen.
Das ist
c = od(e)
in einer Aufzählung.
Mehrzeilig mit Python Syntaxhighlighting:
def f(x):
a = min(0, x)
b = 2 * a + x
return a * b
Zellen können auch "magic commands" beinhalten, welche entweder mit "%
" oder "%%
" beginnen.
%
bezieht sich nur auf die aktuelle Zeile und steht am Beginn.%%
steht zu Beginn der ganzen Zelle und bezieht sich auf die ganze Zelle.Das sind Befehle, welche kein Python sind, sondern nur für IPython und das Notebook bestimmt sind.
Das weiter oben angeführte Beispiel "%whos
" ist so ein magic command.
Andere nützliche sind:
%timeit
bzw. %%time
: um die Ausführungszeit eines Befehls bzw. einer ganzen zu Messen.%reset
: Löschen von gesetzten Variablen%writefile <filename>
: um den Inhalt der Zelle in die angegebene Datei zu speichern.%cat
: Auslesen einer TextdateiEin "!
" Rufzeichen führt den nachgestellten Code im Terminal des Systems aus.
Damit lassen sich lokale Operationen im Dateisystem oder kleine Utilites bequem vom IPython Notebook aus steuern.
Neben diesen gibt es auch noch eine reihe anderer.
Der Magic Befehl "%lsmagics
" listet alle auf.
%lsmagic
Available line magics: %alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %install_default_config %install_ext %install_profiles %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode Available cell magics: %%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile Automagic is ON, % prefix IS NOT needed for line magics.
Beispiel: Benchmark eines Funkionsaufrufs.
import math
%timeit math.sqrt(2)
The slowest run took 41.91 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 144 ns per loop
Das !
ruft den nachgestellten Befehl in der Kommandozeile auf.
! ls -1 2-?-*.ipynb
2-0-konzepte.ipynb 2-1-ausdruecke_und_variablen.ipynb 2-2-syntax-errors.ipynb 2-3-funktionen.ipynb 2-4-kontrollstrukturen.ipynb 2-5-datenstrukturen.ipynb 2-6-datentypen_und_objekte.ipynb 2-7-modularisierung.ipynb
Die Rückgabe so eines Terminalkommandos nach einem Rufzeichen kann auch in eine lokale Variable gespeichert werden:
datum = ! date "+%Y-%m-%d %H:%M"
datum[0]
'2016-05-21 17:53'