From 053e4c99f0c90d3fd852cd7004184a9bc090f2cb 2005-09-22 09:32:46 From: fperez Date: 2005-09-22 09:32:46 Subject: [PATCH] Add sys.argv support for demos. --- diff --git a/IPython/Magic.py b/IPython/Magic.py index 2096c73..48bbbab 100644 --- a/IPython/Magic.py +++ b/IPython/Magic.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """Magic functions for InteractiveShell. -$Id: Magic.py 583 2005-05-13 21:20:33Z fperez $""" +$Id: Magic.py 897 2005-09-22 09:32:46Z fperez $""" #***************************************************************************** # Copyright (C) 2001 Janko Hauser and @@ -21,7 +21,7 @@ __license__ = Release.license # Python standard modules import __builtin__ -import os,sys,inspect,pydoc,re,tempfile,shlex,pdb,bdb,time +import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time try: import profile,pstats except ImportError: @@ -82,42 +82,6 @@ def get_py_filename(name): else: raise IOError,'File `%s` not found.' % name -# Try to use shlex.split for converting an input string into a sys.argv-type -# list. This appeared in Python 2.3, so here's a quick backport for 2.2. -try: - shlex_split = shlex.split -except AttributeError: - _quotesre = re.compile(r'[\'"](.*)[\'"]') - _wordchars = ('abcdfeghijklmnopqrstuvwxyz' - 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' - 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' - 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' - % os.sep) - - def shlex_split(s): - """Simplified backport to Python 2.2 of shlex.split(). - - This is a quick and dirty hack, since the shlex module under 2.2 lacks - several of the features needed to really match the functionality of - shlex.split() in 2.3.""" - - lex = shlex.shlex(StringIO(s)) - # Try to get options, extensions and path separators as characters - lex.wordchars = _wordchars - lex.commenters = '' - # Make a list out of the lexer by hand, since in 2.2 it's not an - # iterator. - lout = [] - while 1: - token = lex.get_token() - if token == '': - break - # Try to handle quoted tokens correctly - quotes = _quotesre.match(token) - if quotes: - token = quotes.group(1) - lout.append(token) - return lout #**************************************************************************** # Utility classes diff --git a/IPython/demo.py b/IPython/demo.py index fcc763f..3810566 100644 --- a/IPython/demo.py +++ b/IPython/demo.py @@ -10,19 +10,40 @@ Sorry, but this uses Python 2.3 features, so it won't work in 2.2 environments. # #***************************************************************************** +import sys import exceptions import re from IPython.PyColorize import Parser -from IPython.genutils import marquee +from IPython.genutils import marquee, shlex_split class DemoError(exceptions.Exception): pass class Demo: - def __init__(self,fname,mark_pause='# pause',mark_silent='# silent', - auto=False): - """The marks are turned into regexps which match them as standalone in - a line, with all leading/trailing whitespace ignored.""" + def __init__(self,fname,arg_str='',mark_pause='# pause', + mark_silent='# silent',auto=False): + """Make a new demo object. To run the demo, simply call the object. + + Inputs: + + - fname = filename. + + Optional inputs: + + - arg_str(''): a string of arguments, internally converted to a list + just like sys.argv, so the demo script can see a similar + environment. + + - mark_pause ('# pause'), mark_silent('# silent'): marks for pausing + (block boundaries) and to tag blocks as silent. The marks are + turned into regexps which match them as standalone in a line, with + all leading/trailing whitespace ignored. + + - auto(False): flag to run each block automatically without + confirmation. Note that silent blocks are always automatically + executed. This flag is an attribute of the object, and can be + changed at runtime simply by reassigning it. + """ self.fname = fname self.mark_pause = mark_pause @@ -30,6 +51,7 @@ class Demo: self.mark_silent = mark_silent self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) self.auto = auto + self.sys_argv = shlex_split(arg_str) # get a few things from ipython. While it's a bit ugly design-wise, # it ensures that things like color scheme and the like are always in @@ -134,8 +156,12 @@ class Demo: if ans: print marquee('Block NOT executed') return - - exec next_block in self.user_ns + try: + save_argv = sys.argv + sys.argv = self.sys_argv + exec next_block in self.user_ns + finally: + sys.argv = save_argv except: self.ip_showtraceback(filename=self.fname) diff --git a/IPython/genutils.py b/IPython/genutils.py index 15a4c4f..73151d4 100644 --- a/IPython/genutils.py +++ b/IPython/genutils.py @@ -5,7 +5,7 @@ General purpose utilities. This is a grab-bag of stuff I find useful in most programs I write. Some of these things are also convenient when working at the command line. -$Id: genutils.py 894 2005-09-22 07:16:18Z fperez $""" +$Id: genutils.py 897 2005-09-22 09:32:46Z fperez $""" #***************************************************************************** # Copyright (C) 2001-2004 Fernando Perez. @@ -24,6 +24,7 @@ __license__ = Release.license # required modules import __main__ import types,commands,time,sys,os,re,shutil +import shlex import tempfile from IPython.Itpl import Itpl,itpl,printpl from IPython import DPyGetOpt @@ -51,6 +52,43 @@ except NameError: __builtin__.False = False __builtin__.enumerate = enumerate +# Try to use shlex.split for converting an input string into a sys.argv-type +# list. This appeared in Python 2.3, so here's a quick backport for 2.2. +try: + shlex_split = shlex.split +except AttributeError: + _quotesre = re.compile(r'[\'"](.*)[\'"]') + _wordchars = ('abcdfeghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' + 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' + 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' + % os.sep) + + def shlex_split(s): + """Simplified backport to Python 2.2 of shlex.split(). + + This is a quick and dirty hack, since the shlex module under 2.2 lacks + several of the features needed to really match the functionality of + shlex.split() in 2.3.""" + + lex = shlex.shlex(StringIO(s)) + # Try to get options, extensions and path separators as characters + lex.wordchars = _wordchars + lex.commenters = '' + # Make a list out of the lexer by hand, since in 2.2 it's not an + # iterator. + lout = [] + while 1: + token = lex.get_token() + if token == '': + break + # Try to handle quoted tokens correctly + quotes = _quotesre.match(token) + if quotes: + token = quotes.group(1) + lout.append(token) + return lout + #**************************************************************************** # Exceptions class Error(Exception): diff --git a/doc/ChangeLog b/doc/ChangeLog index 145cc91..26a6fc6 100644 --- a/doc/ChangeLog +++ b/doc/ChangeLog @@ -1,7 +1,11 @@ 2005-09-22 Fernando Perez + * IPython/genutils.py (shlex_split): moved from Magic to here, + where all 2.2 compatibility stuff lives. I needed it for demo.py. + * IPython/demo.py (Demo.__init__): added support for silent blocks, improved marks as regexps, docstrings written. + (Demo.__init__): better docstring, added support for sys.argv. * IPython/genutils.py (marquee): little utility used by the demo code, handy in general.