Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 98bf043

Browse files
committed
First build of the new IPython website.
0 parents  commit 98bf043

94 files changed

Lines changed: 18479 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.buildinfo

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Sphinx build info version 1
2+
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
3+
config: e849ccc7e4bf7c651d4f9a84608b8d46
4+
tags: fbb0d17656682115ca4d033fb2f83ba1

.nojekyll

Whitespace-only changes.

_images/logo-hpc2008-header.png

14.8 KB
Loading

_sources/c_EmbeddingInGTK.txt

Lines changed: 381 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,381 @@
1+
============================
2+
Embedding Ipython in a PyGTK Application
3+
============================
4+
5+
The Accerciser project has some great code that lets you run an IPython console inside a gtk.TextArea
6+
7+
http://live.gnome.org/Accerciser
8+
9+
The file ipython_view.py seems to be independent in their code, and is licensed under the BSD license. We include a '''modified''' version of the file below.
10+
11+
This has been tested and seems to work in Linux (Ubuntu 6.10 and Fedora Core 6) and Windows (XP with Python 2.4.2, IPython 0.7.3, gtk+-devel 2.10.7, PyGTK 2.10.3). It supports the up/down arrows to view history, and tab completion for commands/variables etc.
12+
13+
Suggestions for improvement very much appreciated! If you find bugs in the ipython_view.py file, please report them to GNOME bugzilla, http://bugzilla.gnome.org/browse.cgi?product=accerciser
14+
15+
**Known bugs**
16+
17+
* The HOME key doesn't return you to the right place when typing a command.
18+
* On Windows, if you type a valid magic function, for example ''%magic'' then it causes your program to hang.
19+
* On Windows, with IPython 0.8.1, colours don't seem to work and tab-completion is not available.
20+
21+
----------
22+
Example
23+
----------
24+
25+
Here is a simple example showing how the IPython console can be embedded in a short Python/PyGTK script to give a basic scrolling terminal window.
26+
27+
..image::logos/ipython-in-pygtk.png
28+
29+
Here is the code::
30+
31+
#!python
32+
import gtk
33+
from ipython_view import *
34+
import pango
35+
36+
import platform
37+
if platform.system()=="Windows":
38+
FONT = "Lucida Console 9"
39+
else:
40+
FONT = "Luxi Mono 10"
41+
42+
W = gtk.Window()
43+
W.set_size_request(750,550)
44+
W.set_resizable(True)
45+
S = gtk.ScrolledWindow()
46+
S.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
47+
V = IPythonView()
48+
V.modify_font(pango.FontDescription(FONT))
49+
V.set_wrap_mode(gtk.WRAP_CHAR)
50+
V.show()
51+
S.add(V)
52+
S.show()
53+
W.add(S)
54+
W.show()
55+
W.connect('delete_event',lambda x,y:False)
56+
W.connect('destroy',lambda x:gtk.main_quit())
57+
gtk.main()
58+
59+
60+
-------------------------------
61+
Exposing variables to the shell
62+
-------------------------------
63+
64+
If you have variables you want to expose in the shell, use the following syntax. Also look at the files in the Accerciser source code for how to synchronise other aspects of your GUI with the actions inthe IPython prompt.::
65+
66+
#!python
67+
V.updateNamespace({'myvar': myvar})
68+
69+
---------------------
70+
ipython_view.py
71+
---------------------
72+
Here is a **modified** version of the [http://svn.gnome.org/svn/accerciser/trunk/plugins/ipython_view.py ipython_view.py] from the Accerciser subversion repository.
73+
74+
Changes relative to the copy in Subversion:
75+
* throw an exception on failed import, instead of remaining silent.
76+
* added ''if argv is None: argv = []'' to fix case of Python being called with commandline args not intended for ipython::
77+
78+
#!python
79+
"""
80+
Backend to the console plugin.
81+
82+
@author: Eitan Isaacson
83+
@organization: IBM Corporation
84+
@copyright: Copyright (c) 2007 IBM Corporation
85+
@license: BSD
86+
87+
All rights reserved. This program and the accompanying materials are made
88+
available under the terms of the BSD which accompanies this distribution, and
89+
is available at U{http://www.opensource.org/licenses/bsd-license.php}
90+
"""
91+
# this file is a modified version of source code from the Accerciser project
92+
# http://live.gnome.org/accerciser
93+
94+
import gtk
95+
import re
96+
import sys
97+
import os
98+
import pango
99+
from StringIO import StringIO
100+
101+
try:
102+
import IPython
103+
except Exception,e:
104+
raise "Error importing IPython (%s)" % str(e)
105+
106+
ansi_colors = {'0;30': 'Black',
107+
'0;31': 'Red',
108+
'0;32': 'Green',
109+
'0;33': 'Brown',
110+
'0;34': 'Blue',
111+
'0;35': 'Purple',
112+
'0;36': 'Cyan',
113+
'0;37': 'LightGray',
114+
'1;30': 'DarkGray',
115+
'1;31': 'DarkRed',
116+
'1;32': 'SeaGreen',
117+
'1;33': 'Yellow',
118+
'1;34': 'LightBlue',
119+
'1;35': 'MediumPurple',
120+
'1;36': 'LightCyan',
121+
'1;37': 'White'}
122+
123+
class IterableIPShell:
124+
def __init__(self,argv=None,user_ns=None,user_global_ns=None,
125+
cin=None, cout=None,cerr=None, input_func=None):
126+
if input_func:
127+
IPython.iplib.raw_input_original = input_func
128+
if cin:
129+
IPython.Shell.Term.cin = cin
130+
if cout:
131+
IPython.Shell.Term.cout = cout
132+
if cerr:
133+
IPython.Shell.Term.cerr = cerr
134+
135+
if argv is None:
136+
argv=[]
137+
138+
# This is to get rid of the blockage that occurs during
139+
# IPython.Shell.InteractiveShell.user_setup()
140+
IPython.iplib.raw_input = lambda x: None
141+
142+
self.term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr)
143+
os.environ['TERM'] = 'dumb'
144+
excepthook = sys.excepthook
145+
self.IP = IPython.Shell.make_IPython(argv,user_ns=user_ns,
146+
user_global_ns=user_global_ns,
147+
embedded=True,
148+
shell_class=IPython.Shell.InteractiveShell)
149+
self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd),
150+
header='IPython system call: ',
151+
verbose=self.IP.rc.system_verbose)
152+
sys.excepthook = excepthook
153+
self.iter_more = 0
154+
self.history_level = 0
155+
self.complete_sep = re.compile('[\s\{\}\[\]\(\)]')
156+
157+
def execute(self):
158+
self.history_level = 0
159+
orig_stdout = sys.stdout
160+
sys.stdout = IPython.Shell.Term.cout
161+
try:
162+
line = self.IP.raw_input(None, self.iter_more)
163+
if self.IP.autoindent:
164+
self.IP.readline_startup_hook(None)
165+
except KeyboardInterrupt:
166+
self.IP.write('\nKeyboardInterrupt\n')
167+
self.IP.resetbuffer()
168+
# keep cache in sync with the prompt counter:
169+
self.IP.outputcache.prompt_count -= 1
170+
171+
if self.IP.autoindent:
172+
self.IP.indent_current_nsp = 0
173+
self.iter_more = 0
174+
except:
175+
self.IP.showtraceback()
176+
else:
177+
self.iter_more = self.IP.push(line)
178+
if (self.IP.SyntaxTB.last_syntax_error and
179+
self.IP.rc.autoedit_syntax):
180+
self.IP.edit_syntax_error()
181+
if self.iter_more:
182+
self.prompt = str(self.IP.outputcache.prompt2).strip()
183+
if self.IP.autoindent:
184+
self.IP.readline_startup_hook(self.IP.pre_readline)
185+
else:
186+
self.prompt = str(self.IP.outputcache.prompt1).strip()
187+
sys.stdout = orig_stdout
188+
189+
def historyBack(self):
190+
self.history_level -= 1
191+
return self._getHistory()
192+
193+
def historyForward(self):
194+
self.history_level += 1
195+
return self._getHistory()
196+
197+
def _getHistory(self):
198+
try:
199+
rv = self.IP.user_ns['In'][self.history_level].strip('\n')
200+
except IndexError:
201+
self.history_level = 0
202+
rv = ''
203+
return rv
204+
205+
def updateNamespace(self, ns_dict):
206+
self.IP.user_ns.update(ns_dict)
207+
208+
def complete(self, line):
209+
split_line = self.complete_sep.split(line)
210+
possibilities = self.IP.complete(split_line[-1])
211+
if possibilities:
212+
common_prefix = reduce(self._commonPrefix, possibilities)
213+
completed = line[:-len(split_line[-1])]+common_prefix
214+
else:
215+
completed = line
216+
return completed, possibilities
217+
218+
def _commonPrefix(self, str1, str2):
219+
for i in range(len(str1)):
220+
if not str2.startswith(str1[:i+1]):
221+
return str1[:i]
222+
return str1
223+
224+
def shell(self, cmd,verbose=0,debug=0,header=''):
225+
stat = 0
226+
if verbose or debug: print header+cmd
227+
# flush stdout so we don't mangle python's buffering
228+
if not debug:
229+
input, output = os.popen4(cmd)
230+
print output.read()
231+
output.close()
232+
input.close()
233+
234+
class ConsoleView(gtk.TextView):
235+
def __init__(self):
236+
gtk.TextView.__init__(self)
237+
self.modify_font(pango.FontDescription('Mono'))
238+
self.set_cursor_visible(True)
239+
self.text_buffer = self.get_buffer()
240+
self.mark = self.text_buffer.create_mark('scroll_mark',
241+
self.text_buffer.get_end_iter(),
242+
False)
243+
for code in ansi_colors:
244+
self.text_buffer.create_tag(code,
245+
foreground=ansi_colors[code],
246+
weight=700)
247+
self.text_buffer.create_tag('0')
248+
self.text_buffer.create_tag('notouch', editable=False)
249+
self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?')
250+
self.line_start = \
251+
self.text_buffer.create_mark('line_start',
252+
self.text_buffer.get_end_iter(), True
253+
)
254+
self.connect('key-press-event', self._onKeypress)
255+
self.last_cursor_pos = 0
256+
257+
def write(self, text, editable=False):
258+
segments = self.color_pat.split(text)
259+
segment = segments.pop(0)
260+
start_mark = self.text_buffer.create_mark(None,
261+
self.text_buffer.get_end_iter(),
262+
True)
263+
self.text_buffer.insert(self.text_buffer.get_end_iter(), segment)
264+
265+
if segments:
266+
ansi_tags = self.color_pat.findall(text)
267+
for tag in ansi_tags:
268+
i = segments.index(tag)
269+
self.text_buffer.insert_with_tags_by_name(self.text_buffer.get_end_iter(),
270+
segments[i+1], tag)
271+
segments.pop(i)
272+
if not editable:
273+
self.text_buffer.apply_tag_by_name('notouch',
274+
self.text_buffer.get_iter_at_mark(start_mark),
275+
self.text_buffer.get_end_iter())
276+
self.text_buffer.delete_mark(start_mark)
277+
self.scroll_mark_onscreen(self.mark)
278+
279+
def showPrompt(self, prompt):
280+
self.write(prompt)
281+
self.text_buffer.move_mark(self.line_start,self.text_buffer.get_end_iter())
282+
283+
def changeLine(self, text):
284+
iter = self.text_buffer.get_iter_at_mark(self.line_start)
285+
iter.forward_to_line_end()
286+
self.text_buffer.delete(self.text_buffer.get_iter_at_mark(self.line_start), iter)
287+
self.write(text, True)
288+
289+
def getCurrentLine(self):
290+
rv = self.text_buffer.get_slice(self.text_buffer.get_iter_at_mark(self.line_start),
291+
self.text_buffer.get_end_iter(), False)
292+
return rv
293+
294+
def showReturned(self, text):
295+
iter = self.text_buffer.get_iter_at_mark(self.line_start)
296+
iter.forward_to_line_end()
297+
self.text_buffer.apply_tag_by_name('notouch',
298+
self.text_buffer.get_iter_at_mark(self.line_start),
299+
iter)
300+
self.write('\n'+text)
301+
if text:
302+
self.write('\n')
303+
self.showPrompt(self.prompt)
304+
self.text_buffer.move_mark(self.line_start,self.text_buffer.get_end_iter())
305+
self.text_buffer.place_cursor(self.text_buffer.get_end_iter())
306+
307+
def _onKeypress(self, obj, event):
308+
if not event.string:
309+
return
310+
insert_mark = self.text_buffer.get_insert()
311+
insert_iter = self.text_buffer.get_iter_at_mark(insert_mark)
312+
selection_mark = self.text_buffer.get_selection_bound()
313+
selection_iter = self.text_buffer.get_iter_at_mark(selection_mark)
314+
start_iter = self.text_buffer.get_iter_at_mark(self.line_start)
315+
if start_iter.compare(insert_iter) <= 0 and \
316+
start_iter.compare(selection_iter) <= 0:
317+
return
318+
elif start_iter.compare(insert_iter) > 0 and \
319+
start_iter.compare(selection_iter) > 0:
320+
self.text_buffer.place_cursor(start_iter)
321+
elif insert_iter.compare(selection_iter) < 0:
322+
self.text_buffer.move_mark(insert_mark, start_iter)
323+
elif insert_iter.compare(selection_iter) > 0:
324+
self.text_buffer.move_mark(selection_mark, start_iter)
325+
326+
327+
class IPythonView(ConsoleView, IterableIPShell):
328+
def __init__(self):
329+
ConsoleView.__init__(self)
330+
self.cout = StringIO()
331+
IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout,
332+
input_func=self.raw_input)
333+
self.connect('key_press_event', self.keyPress)
334+
self.execute()
335+
self.cout.truncate(0)
336+
self.showPrompt(self.prompt)
337+
self.interrupt = False
338+
339+
def raw_input(self, prompt=''):
340+
if self.interrupt:
341+
self.interrupt = False
342+
raise KeyboardInterrupt
343+
return self.getCurrentLine()
344+
345+
def keyPress(self, widget, event):
346+
if event.state & gtk.gdk.CONTROL_MASK and event.keyval == 99:
347+
self.interrupt = True
348+
self._processLine()
349+
return True
350+
elif event.keyval == gtk.keysyms.Return:
351+
self._processLine()
352+
return True
353+
elif event.keyval == gtk.keysyms.Up:
354+
self.changeLine(self.historyBack())
355+
return True
356+
elif event.keyval == gtk.keysyms.Down:
357+
self.changeLine(self.historyForward())
358+
return True
359+
elif event.keyval == gtk.keysyms.Tab:
360+
if not self.getCurrentLine().strip():
361+
return False
362+
completed, possibilities = self.complete(self.getCurrentLine())
363+
if len(possibilities) > 1:
364+
slice = self.getCurrentLine()
365+
self.write('\n')
366+
for symbol in possibilities:
367+
self.write(symbol+'\n')
368+
self.showPrompt(self.prompt)
369+
self.changeLine(completed or slice)
370+
return True
371+
372+
def _processLine(self):
373+
self.history_pos = 0
374+
self.execute()
375+
rv = self.cout.getvalue()
376+
if rv: rv = rv.strip('\n')
377+
self.showReturned(rv)
378+
self.cout.truncate(0)
379+
380+
381+

0 commit comments

Comments
 (0)