Help - command line arguments

Hans Nowak wurmy at earthlink.net
Sun Dec 30 00:36:20 EST 2001


Steve Zatz wrote:
> 
> I am new to Python and although I am sure that the following is obvious I
> can't figure the following out or find an answer in any of the texts that I
> have access to.
> 
> My question is:  Can you run a script that takes command line arguments from
> within the Python shell or from the Python command line?
> 
> For example, something like:
> 
> 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.

You can mess around with sys.argv, but I'm not sure if that
is kosher...

>>> import sys
>>> sys.argv[0] = 'myself.py'
>>> sys.argv[1:] = '-x foo -y bla filename'.split()
>>> sys.argv
['myself.py', '-x', 'foo', '-y', 'bla', 'filename']
>>> 

If the program defines a "if __name__ == "__main__"
block, you're out of luck, though. import will not execute
the code in the block.

--Hans



More information about the Python-list mailing list