run a python application inside the python shell

Doug Stanfield DOUGS at oceanic.com
Tue Oct 24 15:58:31 EDT 2000


If you are used to programming by putting together a procedural script you
won't be able to easily do this.  If the following were named breakfast.py:

#!/usr/bin/env python
import sys
spam = 22
eggs = 3
ketchup = 0
rice = "the food of gods"
if len(sys.argv) > 0:
    ketchup = 1
try:
    food = [('no','some','lots of')[int(spam/8.0)]]
except IndexError:
    food = ['great heaps of']
food.append(eggs)
food.append(rice)
print "I want %s spam, %s eggs, and rice, %s." % tuple(food)
if ketchup:
    print "Pour some of da kine ova hea."

This is run from the command line:
> spam.py
   -or-
> python spam.py

If you want to use this inside the interactive interpreter (I assume that is
what you mean by the shell) rewrite to make it a module:

#!/usr/bin/env python
import sys

def serve(spam,eggs,rice,ketchup=0):
    try:
        food = [('no','some','lots of')[int(spam/8.0)]]
    except IndexError:
        food = ['great heaps of']
    food.append(eggs)
    food.append(rice)
    dish = "I want %s spam, %s eggs and rice, %s." % tuple(food)
    if ketchup:
        dish = dish + "\nPour some of dat ova hea."
    return dish

if __name__ == '__main__':
    spam = 22
    eggs = 3
    ketchup = 0
    rice = "the food of gods"
    print sys.argv
    if len(sys.argv) > 1:
        print serve(spam,eggs,rice,ketchup=1)
    else:
        print serve(spam,eggs,rice)

This way it still runs from the command line as before or you can enter the
interpreter and play with it:
> python
Python 1.5.2 (#1, Apr 18 1999, 16:03:16)  [GCC pgcc-2.91.60 19981201
(egcs-1.1.1  on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import breakfast
>>> print breakfast.serve(0,1,"lots of it")
I want no spam, 1 eggs and rice, lots of it.
>>> 

I hope that was what you were asking.  ;-)

-Doug-

> -----Original Message-----
> From: Hwanjo Yu [mailto:hwanjoyu at uiuc.edu]
> Sent: Tuesday, October 24, 2000 8:25 AM
> To: python-list at python.org
> Subject: Q: run a python application inside the python shell
> 
> 
> Hi,
> 
> How to run a python application inside the python shell ?
> Thanks in advance.
> 
> 
> 
> -- 
> http://www.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list