REPOST: Re: 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

========= WAS CANCELLED BY =======:
Path: news.sol.net!spool0-nwblwi.newsops.execpc.com!newsfeeds.sol.net!newspump.sol.net!nntp1.roc.gblx.net!nntp.gblx.net!nntp1.phx1.gblx.net!nntp.gblx.net!nntp.gblx.net!enews.sgi.com!news-xfer.nuri.net!feeder.kornet.net!news1.kornet.net!ua4canc3ll3r
From: Hans Nowak <wurmy at earthlink.net>
Newsgroups: comp.lang.python
Subject: cmsg cancel <3C2EA674.F6C69FB2 at earthlink.net>
Control: cancel <3C2EA674.F6C69FB2 at earthlink.net>
Date: Mon, 31 Dec 2001 03:38:45 GMT
Organization: A poorly-installed InterNetNews site
Lines: 2
Message-ID: <cancel.3C2EA674.F6C69FB2 at earthlink.net>
NNTP-Posting-Host: 211.57.49.2
X-Trace: news2.kornet.net 1009774376 27193 211.57.49.2 (31 Dec 2001 04:52:56 GMT)
X-Complaints-To: usenet at news2.kornet.net
NNTP-Posting-Date: Mon, 31 Dec 2001 04:52:56 +0000 (UTC)
X-No-Archive: yes
X-Unac4ncel: yes
X-Commentary: I love NewsAgent 1.10 and the Sandblaster Cancel Engine Build 74 (19 March 1999)

This message was cancelled from within Mozilla.



More information about the Python-list mailing list