[IPython-user] python vs. ipython

Peter Teuben teuben at astro.umd.edu
Thu Jan 26 21:05:40 CST 2006


after some hiatus of doing other things, i wanted to come back to the issue
of running scripts with arguments from ipython:

On Tue, 25 Oct 2005, Fernando Perez wrote:
....
> If you simply say
>
> ipython yourscript.py
>
> it will work, with the caveat that sys.argv will include ipython as the first
> entry.  It would be possible to add a --run option which would work as follows:
>
> ipython --foo --bar --run "yourscript.py --opt1 arg1"
...

after some renewed tinkering, i was able to kludge up a python script, 
that can be run from python and ipython directly into interactive mode:

 	python -i hello.py a b c
vs.
 	ipython -c 'main("a b c".split())' hello.py

The main() kludge  is rather ugly, but i think will work. Is does however 
require the script to write a main() in which global variables may need to
be imported to be visible at the global scope. Here's my hello world example:

#

import sys

mode = "unknown"

def main(Argv=[],ipython=True):
     """main entry point for both python and ipython"""
     global mode
     print Argv
     if ipython:
         print "main(ipython) - type 'Exit' to exit (^D also works)"
         mode = 'ipython'
     else:
         print "main(python)  - type ^D to exit"
         mode = 'python'

if __name__ == '__main__' :
     if sys.argv[0][-7:] != "ipython":
         main(sys.argv[1:],False)
# don't do any more work after this line, all of __main__ should occur in main()



Once in interactive mode, the user has access to the 'mode' variable, which
has either "python" or "ipython" as its value.

Perhaps we can get a "--run" flag into ipython, or perhaps there are other
creative solutions to this problem.

- peter




More information about the IPython-user mailing list