REPOST: Help - command line arguments
Alex Martelli
aleax at aleax.it
Wed Jan 2 07:17:54 EST 2002
"Steve Zatz" <slzatz at hotmail.com> wrote in message
news:7$--$$_----__%--%$@news.noc.cabal.int...
...
> test.py -a -b
>
> runs fine from the *Windows XP* command prompt.
>
> From the Python command line, I can do the following:
>
> import test
> test.main()
>
> which doesn't produce an exception but I can't figure out how to input the
> command line arguments.
import sys
sys.argv = "test.py -a -b".split()
import test
test.main()
However, this does differ in one important respect from running
test at the command prompt. When you do the latter, then, within
test.py, global variable __name__ is set to the string '__main__'.
With this approach, on the other hand, it's set to '__test__'.
This is how a script tells whether it's being run, or imported
as a module. If you want to make the script BELIEVE it's being
imported, you CAN, though it IS slightly tricky:
import sys
sys.argv = "test.py -a -b".split()
import imp
imp.load_module('__main__',*imp.find_module('test'))
this makes the module believe its name is __main__, i.e., that
it's being run as a script rather than imported. If the script
is not on the sys.path (which is what implicity gets searched
by imp.find_module), just pass the directory as the second
argument of find_module (you can automate this with os.path.split
and os.path.splitext).
If you do this often, you're best off making this into a function
and sticking it into __builtins__ from sitecustomize.py.
Alex
More information about the Python-list
mailing list