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