[IPython-user] Changing context in iPython CLI

Fernando Perez Fernando.Perez at colorado.edu
Thu Oct 6 15:46:51 CDT 2005


DogWalker wrote:
> "Chris Youb" <nfn_nln at hotmail.com> said:
> 
> 
>>I use the iPython shell as a command-line interface for one of my programs.
>>Unfortunately, I repeatedly have to prefix my commands with the variable name
>>I've setup.  Is there any way to change/imply context in iPython.  Here is an
>>example of what I mean using an instance of a String for simplicity:
>>
>>This is what I do now:
>>
>>In [2]: x.lower()
>>Out[2]: 'this is a string!'
>>
>>In [3]: x.swapcase()
>>Out[3]: 'tHIS IS A sTRING!'
>>
>>When I'd really just like to type this:
>>
>>In [2]: lower()
>>Out[2]: 'this is a string!'
>>
>>In [3]: swapcase()
>>Out[3]: 'tHIS IS A sTRING!'
>>
> 
> 
> Define a function to return what you want:
> 
> def lower():return x.lower()

I think that the OP wants something a bit more automatic than that, so that he 
can quickly change over to another object and have all typed input be applied 
to it.

What the OP wants is not in any way part of standard python, but given that 
ipython is fully customizable, it's perfectly doable.  But it requires a bit 
of hacking.

Looking at how the pysh profile is implemented is probably the best way, 
because this will require writing a custom input preprocessor, which prepends 
an arbitrary string to all input.  In combination with a magic, you can get 
what you want.  Here's how you can make it work:

%autoprepend x.
All new input prepended with 'x.' from now on...

When you want it off, you just type

%autoprepend
Auto prened disabled.

And you'd write a custom .prefilter() method which would prepend this string 
to all input not starting with a custom escape (so you can still use magics 
and such).

The pysh code lives in IPython/Extensions, and there you will also find other 
input customization examples.

Cheers,

f




More information about the IPython-user mailing list