##// END OF EJS Templates
Improve Python 3 compatibility for example scripts.
Thomas Kluyver -
Show More
@@ -1,101 +1,99 b''
1 1 """A simple example of how to use IPython.config.application.Application.
2 2
3 3 This should serve as a simple example that shows how the IPython config
4 4 system works. The main classes are:
5 5
6 6 * IPython.config.configurable.Configurable
7 7 * IPython.config.configurable.SingletonConfigurable
8 8 * IPython.config.loader.Config
9 9 * IPython.config.application.Application
10 10
11 11 To see the command line option help, run this program from the command line::
12 12
13 13 $ python appconfig.py -h
14 14
15 15 To make one of your classes configurable (from the command line and config
16 16 files) inherit from Configurable and declare class attributes as traits (see
17 17 classes Foo and Bar below). To make the traits configurable, you will need
18 18 to set the following options:
19 19
20 20 * ``config``: set to ``True`` to make the attribute configurable.
21 21 * ``shortname``: by default, configurable attributes are set using the syntax
22 22 "Classname.attributename". At the command line, this is a bit verbose, so
23 23 we allow "shortnames" to be declared. Setting a shortname is optional, but
24 24 when you do this, you can set the option at the command line using the
25 25 syntax: "shortname=value".
26 26 * ``help``: set the help string to display a help message when the ``-h``
27 27 option is given at the command line. The help string should be valid ReST.
28 28
29 29 When the config attribute of an Application is updated, it will fire all of
30 30 the trait's events for all of the config=True attributes.
31 31 """
32 32
33 import sys
34
35 33 from IPython.config.configurable import Configurable
36 34 from IPython.config.application import Application
37 35 from IPython.utils.traitlets import (
38 36 Bool, Unicode, Int, Float, List, Dict
39 37 )
40 38
41 39
42 40 class Foo(Configurable):
43 41 """A class that has configurable, typed attributes.
44 42
45 43 """
46 44
47 45 i = Int(0, config=True, help="The integer i.")
48 46 j = Int(1, config=True, help="The integer j.")
49 47 name = Unicode(u'Brian', config=True, help="First name.")
50 48
51 49
52 50 class Bar(Configurable):
53 51
54 52 enabled = Bool(True, config=True, help="Enable bar.")
55 53
56 54
57 55 class MyApp(Application):
58 56
59 57 name = Unicode(u'myapp')
60 58 running = Bool(False, config=True,
61 59 help="Is the app running?")
62 60 classes = List([Bar, Foo])
63 61 config_file = Unicode(u'', config=True,
64 62 help="Load this config file")
65 63
66 64 aliases = Dict(dict(i='Foo.i',j='Foo.j',name='Foo.name', running='MyApp.running',
67 65 enabled='Bar.enabled', log_level='MyApp.log_level'))
68 66
69 67 flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Enable Bar"),
70 68 disable=({'Bar': {'enabled' : False}}, "Disable Bar"),
71 69 debug=({'MyApp':{'log_level':10}}, "Set loglevel to DEBUG")
72 70 ))
73 71
74 72 def init_foo(self):
75 73 # Pass config to other classes for them to inherit the config.
76 74 self.foo = Foo(config=self.config)
77 75
78 76 def init_bar(self):
79 77 # Pass config to other classes for them to inherit the config.
80 78 self.bar = Bar(config=self.config)
81 79
82 80 def initialize(self, argv=None):
83 81 self.parse_command_line(argv)
84 82 if self.config_file:
85 83 self.load_config_file(self.config_file)
86 84 self.init_foo()
87 85 self.init_bar()
88 86
89 87 def start(self):
90 print "app.config:"
91 print self.config
88 print("app.config:")
89 print(self.config)
92 90
93 91
94 92 def main():
95 93 app = MyApp()
96 94 app.initialize()
97 95 app.start()
98 96
99 97
100 98 if __name__ == "__main__":
101 99 main()
@@ -1,38 +1,37 b''
1 1 #!/usr/bin/env python
2 2 """Extract a session from the IPython input history.
3 3
4 4 Usage:
5 5 ipython-get-history.py sessionnumber [outputfile]
6 6
7 7 If outputfile is not given, the relevant history is written to stdout. If
8 8 outputfile has a .py extension, the translated history (without IPython's
9 9 special syntax) will be extracted.
10 10
11 11 Example:
12 12 ./ipython-get-history.py 57 record.ipy
13 13
14 14
15 15 This script is a simple demonstration of HistoryAccessor. It should be possible
16 16 to build much more flexible and powerful tools to browse and pull from the
17 17 history database.
18 18 """
19 19 import sys
20 import codecs
21 20
22 21 from IPython.core.history import HistoryAccessor
23 22
24 23 session_number = int(sys.argv[1])
25 24 if len(sys.argv) > 2:
26 25 dest = open(sys.argv[2], "w")
27 26 raw = not sys.argv[2].endswith('.py')
28 27 else:
29 28 dest = sys.stdout
30 29 raw = True
31 30 dest.write("# coding: utf-8\n")
32 31
33 32 # Profiles other than 'default' can be specified here with a profile= argument:
34 33 hist = HistoryAccessor()
35 34
36 35 for session, lineno, cell in hist.get_range(session=session_number, raw=raw):
37 # To use this in Python 3, remove the .encode() here:
38 dest.write(cell.encode('utf-8') + '\n')
36 cell = cell.encode('utf-8') # This line is only needed on Python 2.
37 dest.write(cell + '\n')
@@ -1,45 +1,46 b''
1 from __future__ import print_function
1 2 import os
2 3
3 4 from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
4 5 from IPython.qt.inprocess import QtInProcessKernelManager
5 6 from IPython.lib import guisupport
6 7
7 8
8 9 def print_process_id():
9 print 'Process ID is:', os.getpid()
10 print('Process ID is:', os.getpid())
10 11
11 12
12 13 def main():
13 14 # Print the ID of the main process
14 15 print_process_id()
15 16
16 17 app = guisupport.get_app_qt4()
17 18
18 19 # Create an in-process kernel
19 20 # >>> print_process_id()
20 21 # will print the same process ID as the main process
21 22 kernel_manager = QtInProcessKernelManager()
22 23 kernel_manager.start_kernel()
23 24 kernel = kernel_manager.kernel
24 25 kernel.gui = 'qt4'
25 26 kernel.shell.push({'foo': 43, 'print_process_id': print_process_id})
26 27
27 28 kernel_client = kernel_manager.client()
28 29 kernel_client.start_channels()
29 30
30 31 def stop():
31 32 kernel_client.stop_channels()
32 33 kernel_manager.shutdown_kernel()
33 34 app.exit()
34 35
35 36 control = RichIPythonWidget()
36 37 control.kernel_manager = kernel_manager
37 38 control.kernel_client = kernel_client
38 39 control.exit_requested.connect(stop)
39 40 control.show()
40 41
41 42 guisupport.start_event_loop_qt4(app)
42 43
43 44
44 45 if __name__ == '__main__':
45 46 main()
@@ -1,30 +1,31 b''
1 from __future__ import print_function
1 2 import os
2 3
3 4 from IPython.kernel.inprocess import InProcessKernelManager
4 5 from IPython.terminal.console.interactiveshell import ZMQTerminalInteractiveShell
5 6
6 7
7 8 def print_process_id():
8 print 'Process ID is:', os.getpid()
9 print('Process ID is:', os.getpid())
9 10
10 11
11 12 def main():
12 13 print_process_id()
13 14
14 15 # Create an in-process kernel
15 16 # >>> print_process_id()
16 17 # will print the same process ID as the main process
17 18 kernel_manager = InProcessKernelManager()
18 19 kernel_manager.start_kernel()
19 20 kernel = kernel_manager.kernel
20 21 kernel.gui = 'qt4'
21 22 kernel.shell.push({'foo': 43, 'print_process_id': print_process_id})
22 23 client = kernel_manager.client()
23 24 client.start_channels()
24 25
25 26 shell = ZMQTerminalInteractiveShell(manager=kernel_manager, client=client)
26 27 shell.mainloop()
27 28
28 29
29 30 if __name__ == '__main__':
30 31 main()
@@ -1,41 +1,40 b''
1 1 #!/usr/bin/env python
2 2 """Simple Qt4 example to manually test event loop integration.
3 3
4 4 This is meant to run tests manually in ipython as:
5 5
6 6 In [5]: %gui qt
7 7
8 8 In [6]: %run gui-qt.py
9 9
10 10 Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/
11 11 """
12 12
13 import sys
14 13 from PyQt4 import QtGui, QtCore
15 14
16 15 class SimpleWindow(QtGui.QWidget):
17 16 def __init__(self, parent=None):
18 17 QtGui.QWidget.__init__(self, parent)
19 18
20 19 self.setGeometry(300, 300, 200, 80)
21 20 self.setWindowTitle('Hello World')
22 21
23 22 quit = QtGui.QPushButton('Close', self)
24 23 quit.setGeometry(10, 10, 60, 35)
25 24
26 25 self.connect(quit, QtCore.SIGNAL('clicked()'),
27 26 self, QtCore.SLOT('close()'))
28 27
29 28 if __name__ == '__main__':
30 29 app = QtCore.QCoreApplication.instance()
31 30 if app is None:
32 31 app = QtGui.QApplication([])
33 32
34 33 sw = SimpleWindow()
35 34 sw.show()
36 35
37 36 try:
38 37 from IPython.lib.guisupport import start_event_loop_qt4
39 38 start_event_loop_qt4(app)
40 39 except ImportError:
41 40 app.exec_()
@@ -1,32 +1,35 b''
1 1 #!/usr/bin/env python
2 2 """Simple Tk example to manually test event loop integration.
3 3
4 4 This is meant to run tests manually in ipython as:
5 5
6 6 In [5]: %gui tk
7 7
8 8 In [6]: %run gui-tk.py
9 9 """
10 10
11 from Tkinter import *
11 try:
12 from tkinter import * # Python 3
13 except ImportError:
14 from Tkinter import * # Python 2
12 15
13 16 class MyApp:
14 17
15 18 def __init__(self, root):
16 19 frame = Frame(root)
17 20 frame.pack()
18 21
19 22 self.button = Button(frame, text="Hello", command=self.hello_world)
20 23 self.button.pack(side=LEFT)
21 24
22 25 def hello_world(self):
23 26 print("Hello World!")
24 27
25 28 root = Tk()
26 29
27 30 app = MyApp(root)
28 31
29 32 try:
30 33 from IPython.lib.inputhook import enable_tk; enable_tk(root)
31 34 except ImportError:
32 35 root.mainloop()
@@ -1,59 +1,58 b''
1 1 #-----------------------------------------------------------------------------
2 2 # Imports
3 3 #-----------------------------------------------------------------------------
4 4
5 import subprocess
6 5 import sys
7 6
8 7 from IPython.lib.kernel import connect_qtconsole
9 8 from IPython.kernel.zmq.kernelapp import IPKernelApp
10 9
11 10 #-----------------------------------------------------------------------------
12 11 # Functions and classes
13 12 #-----------------------------------------------------------------------------
14 13 def pylab_kernel(gui):
15 14 """Launch and return an IPython kernel with pylab support for the desired gui
16 15 """
17 16 kernel = IPKernelApp.instance()
18 17 kernel.initialize(['python', '--pylab=%s' % gui,
19 18 #'--log-level=10'
20 19 ])
21 20 return kernel
22 21
23 22
24 23 class InternalIPKernel(object):
25 24
26 25 def init_ipkernel(self, backend):
27 26 # Start IPython kernel with GUI event loop and pylab support
28 27 self.ipkernel = pylab_kernel(backend)
29 28 # To create and track active qt consoles
30 29 self.consoles = []
31 30
32 31 # This application will also act on the shell user namespace
33 32 self.namespace = self.ipkernel.shell.user_ns
34 33 # Keys present at startup so we don't print the entire pylab/numpy
35 34 # namespace when the user clicks the 'namespace' button
36 35 self._init_keys = set(self.namespace.keys())
37 36
38 37 # Example: a variable that will be seen by the user in the shell, and
39 38 # that the GUI modifies (the 'Counter++' button increments it):
40 39 self.namespace['app_counter'] = 0
41 40 #self.namespace['ipkernel'] = self.ipkernel # dbg
42 41
43 42 def print_namespace(self, evt=None):
44 43 print("\n***Variables in User namespace***")
45 for k, v in self.namespace.iteritems():
44 for k, v in self.namespace.items():
46 45 if k not in self._init_keys and not k.startswith('_'):
47 46 print('%s -> %r' % (k, v))
48 47 sys.stdout.flush()
49 48
50 49 def new_qt_console(self, evt=None):
51 50 """start a new qtconsole connected to our kernel"""
52 51 return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile)
53 52
54 53 def count(self, evt=None):
55 54 self.namespace['app_counter'] += 1
56 55
57 56 def cleanup_consoles(self, evt=None):
58 57 for c in self.consoles:
59 58 c.kill()
General Comments 0
You need to be logged in to leave comments. Login now