script that parses command line, and execfile('')

Diez B. Roggisch deets at nospam.web.de
Mon Nov 3 14:43:13 EST 2008


TP schrieb:
> Hello,
> 
> I have a script that uses the "optparse" package to parse the command line.
> For example:
> 
> $ script.py --help
> # displays help about script.py
> 
> Is this possible to call such a script with execfile('') once in the Python
> interactive shell?
> 
>>>> execfile( 'script.py' )
> 
> I get errors because there is no argv dictionary when used with execfile.
> 
> How to solve this problem, so that I am able to use script.py in command
> line as well as with execfile?


Don't use execfile. Make script.py like this:


...

def main(argv=None):
     if argv is None: argv = sys.argv[1:]
     ...


Then just do

import script
script.main(arguments)


instead.

Diez



More information about the Python-list mailing list