Поиск по блогу

четверг, 6 марта 2014 г.

A few things that work best/only at the IPython terminal or Qt console clients (10) "... SciPy2013 Tutorial, Part 3 of 3"

На 15 минуте 40 секунде решили поговорить о консольных командах. В перовом примере был записан на диск файл "%%file script.py", а потом выполнен "%run script" ... Во втором примере был также записан файл с делением на ноль и импортом модуля, при остановке "where the notebook still lags the terminal and qt consoles" ... В видео показывается, что qt console подключена к пространству имен ядра и может его изменять.... Справка по %run ... Пример с %debug (только в видео на 22 минуте) Потом "The %gui magic enables the integration of GUI event loops with the interactive execution loop" ... %connect_info %logstart %notebook

Running code with %run

In [6]:
%%file script.py
x = 10
y = 20
z = x+y
print 'z is:', z
Writing script.py

In [7]:
%run script
z is: 30

In [8]:
x
Out[8]:
10
In [23]:
%%file err.py
import mod
mod.g(0)
Overwriting err.py

In [10]:
%run err
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
C:\Users\kiss\Anaconda\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
    195             else:
    196                 filename = fname
--> 197             exec compile(scripttext, filename, 'exec') in glob, loc
    198     else:
    199         def execfile(fname, *where):

C:\Users\kiss\Documents\GitHub\ipython-in-depth\notebooks\err.py in <module>()
----> 1 import mod
      2 mod.g(0)

ImportError: No module named mod
This is the one important point where the notebook still lags the terminal and qt consoles: it can not deal with interactive input from the underlying Python process, which precludes its use for interactive debugging (or anything else that calls raw_input, for that matter). But in the terminal, you can use %debug to enter the interactive debugger any time after an exception has been thrown.
В видеоролике используется qt console, но не говорится о том, как ее запустить. Я помню, что есть возможность подключить к одному ядру сразу несколько терминалов. Забыл, где это прочитал, но нашел магическую команду...
In [5]:
#    Open a qtconsole connected to this kernel.
%qtconsole
In []:
Python 2.7.5 |Anaconda 1.9.0 (64-bit)| (default, Jul  1 2013, 12:37:52) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
%guiref   -> A brief reference about the graphical user interface.

In [6]: 
А как из консоли посмотреть ячейку In[5] напрмер? Для этого можно использовать клавиши со стрелками "вверх"-"вниз"... А вообще-то надо смотреть хелпер в консоли qt (там еще %magic подсказки есть в меню)
In [17]:
%run
%run:
Run the named file inside IPython as a program.

Usage:
  %run [-n -i -e -G]
       [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
       ( -m mod | file ) [args]

Parameters after the filename are passed as command-line arguments to
the program (put in sys.argv). Then, control returns to IPython's
prompt.

This is similar to running at a system prompt:\
  $ python file args\
but with the advantage of giving you IPython's tracebacks, and of
loading all variables into your interactive namespace for further use
(unless -p is used, see below).

The file is executed in a namespace initially consisting only of
__name__=='__main__' and sys.argv constructed as indicated. It thus
sees its environment as if it were being run as a stand-alone program
(except for sharing global objects such as previously imported
modules). But after execution, the IPython interactive namespace gets
updated with all variables defined in the program (except for __name__
and sys.argv). This allows for very convenient loading of code for
interactive work, while giving each program a 'clean sheet' to run in.

Arguments are expanded using shell-like glob match.  Patterns
'*', '?', '[seq]' and '[!seq]' can be used.  Additionally,
tilde '~' will be expanded into user's home directory.  Unlike
real shells, quotation does not suppress expansions.  Use
*two* back slashes (e.g., '\\*') to suppress expansions.
To completely disable these expansions, you can use -G flag.

Options:

-n: __name__ is NOT set to '__main__', but to the running file's name
without extension (as python does under import).  This allows running
scripts and reloading the definitions in them without calling code
protected by an ' if __name__ == "__main__" ' clause.

-i: run the file in IPython's namespace instead of an empty one. This
is useful if you are experimenting with code written in a text editor
which depends on variables defined interactively.

-e: ignore sys.exit() calls or SystemExit exceptions in the script
being run.  This is particularly useful if IPython is being used to
run unittests, which always exit with a sys.exit() call.  In such
cases you are interested in the output of the test results, not in
seeing a traceback of the unittest module.

-t: print timing information at the end of the run.  IPython will give
you an estimated CPU time consumption for your script, which under
Unix uses the resource module to avoid the wraparound problems of
time.clock().  Under Unix, an estimate of time spent on system tasks
is also given (for Windows platforms this is reported as 0.0).

If -t is given, an additional -N<N> option can be given, where <N>
must be an integer indicating how many times you want the script to
run.  The final timing report will include total and per run results.

For example (testing the script uniq_stable.py)::

    In [1]: run -t uniq_stable

    IPython CPU timings (estimated):\
      User  :    0.19597 s.\
      System:        0.0 s.\

    In [2]: run -t -N5 uniq_stable

    IPython CPU timings (estimated):\
    Total runs performed: 5\
      Times :      Total       Per run\
      User  :   0.910862 s,  0.1821724 s.\
      System:        0.0 s,        0.0 s.

-d: run your program under the control of pdb, the Python debugger.
This allows you to execute your program step by step, watch variables,
etc.  Internally, what IPython does is similar to calling:

  pdb.run('execfile("YOURFILENAME")')

with a breakpoint set on line 1 of your file.  You can change the line
number for this automatic breakpoint to be <N> by using the -bN option
(where N must be an integer).  For example::

  %run -d -b40 myscript

will set the first breakpoint at line 40 in myscript.py.  Note that
the first breakpoint must be set on a line which actually does
something (not a comment or docstring) for it to stop execution.

Or you can specify a breakpoint in a different file::

  %run -d -b myotherfile.py:20 myscript

When the pdb debugger starts, you will see a (Pdb) prompt.  You must
first enter 'c' (without quotes) to start execution up to the first
breakpoint.

Entering 'help' gives information about the use of the debugger.  You
can easily see pdb's full documentation with "import pdb;pdb.help()"
at a prompt.

-p: run program under the control of the Python profiler module (which
prints a detailed report of execution times, function calls, etc).

You can pass other options after -p which affect the behavior of the
profiler itself. See the docs for %prun for details.

In this mode, the program's variables do NOT propagate back to the
IPython interactive namespace (because they remain in the namespace
where the profiler executes them).

Internally this triggers a call to %prun, see its documentation for
details on the options available specifically for profiling.

There is one special usage for which the text above doesn't apply:
if the filename ends with .ipy, the file is run as ipython script,
just as if the commands were written on IPython prompt.

-m: specify module name to load instead of script path. Similar to
the -m option for the python interpreter. Use this option last if you
want to combine with other %run options. Unlike the python interpreter
only source modules are allowed no .pyc or .pyo files.
For example::

    %run -m example

will run the example module.

-G: disable shell-like glob expansion of arguments.

WARNING: you must provide at least a filename.

Вот, например, как можно выполнить скрипт с включенным дебаггером:
In [21]:
 %run -d script.py
Breakpoint 1 at c:\users\kiss\documents\github\ipython-in-depth\notebooks\script.py:1
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.
> c:\users\kiss\documents\github\ipython-in-depth\notebooks\script.py(1)<module>()
1---> 1 x = 10
      2 y = 20
      3 z = x+y

ipdb> 
ipdb> n
> c:\users\kiss\documents\github\ipython-in-depth\notebooks\script.py(2)<module>()
1     1 x = 10
----> 2 y = 20
      3 z = x+y

ipdb> n
> c:\users\kiss\documents\github\ipython-in-depth\notebooks\script.py(3)<module>()
      2 y = 20
----> 3 z = x+y
      4 print 'z is:', z

ipdb> n
> c:\users\kiss\documents\github\ipython-in-depth\notebooks\script.py(4)<module>()
      2 y = 20
      3 z = x+y
----> 4 print 'z is:', z

ipdb> n
z is: 30
--Return--
None
> c:\users\kiss\documents\github\ipython-in-depth\notebooks\script.py(4)<module>()
      2 y = 20
      3 z = x+y
----> 4 print 'z is:', z

ipdb> c

А вот полезная команда с инструкцией, как подключится к определенному ядру:
In [31]:
%connect_info
{
  "stdin_port": 56057, 
  "ip": "127.0.0.1", 
  "control_port": 56058, 
  "hb_port": 56059, 
  "signature_scheme": "hmac-sha256", 
  "key": "a56bc680-3001-4d7d-bc2b-30484551870f", 
  "shell_port": 56055, 
  "transport": "tcp", 
  "iopub_port": 56056
}

Paste the above JSON into a file, and connect with:
    $> ipython <app> --existing <file>
or, if you are local, you can connect with just:
    $> ipython <app> --existing kernel-6b0d343a-dab4-49f3-ac83-bab93f0c2aef.json 
or even just:
    $> ipython <app> --existing 
if this is the most recent IPython session you have started.

Event loop and GUI integration

The %gui magic enables the integration of GUI event loops with the interactive execution loop, allowing you to run GUI code without blocking IPython.
Consider for example the execution of Qt-based code. Once we enable the Qt gui support:
In [1]:
%gui qt
We can define a simple Qt application class (simplified version from this Qt tutorial):
In [2]:
import sys
from PyQt4 import QtGui, QtCore

class SimpleWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 200, 80)
        self.setWindowTitle('Hello World')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
                     self, QtCore.SLOT('close()'))
And now we can instantiate it:
In [3]:
app = QtCore.QCoreApplication.instance()
if app is None:
    app = QtGui.QApplication([])

sw = SimpleWindow()
sw.show()

from IPython.lib.guisupport import start_event_loop_qt4
start_event_loop_qt4(app)
But IPython still remains responsive:
In [4]:
10+2
Out[4]:
12
The %gui magic can be similarly used to control Wx, Tk, glut and pyglet applications, as can be seen in our examples.

Embedding IPython in a terminal application

In [28]:
%%file simple-embed.py
# This shows how to use the new top-level embed function.  It is a simpler
# API that manages the creation of the embedded shell.

from IPython import embed

a = 10
b = 20

embed(header='First time', banner1='')

c = 30
d = 40

embed(header='The second time')
Writing simple-embed.py
Overwriting simple-embed.py

The example in kernel-embedding shows how to embed a full kernel into an application and how to connect to this kernel from an external process.

Logging terminal sessions and transitioning to a notebook

The %logstart magic lets you log a terminal session with various degrees of control, and the %notebook one will convert an interactive console session into a notebook with all input cells already created for you (but no output).
In []:



Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий