[Tutor] A question about sys.argv

Jose Amoreira ljmamoreira at gmail.com
Tue Nov 1 15:19:26 CET 2011


HiOn Tuesday, November 01, 2011 01:55:18 PM Joel Goldstick wrote:
> On Tue, Nov 1, 2011 at 9:48 AM, Jefferson Ragot <jbr5393 at gmail.com> wrote:
> > In a Vista command prompt if I typed this:
> >         >>> python  somescript.py  filename
> > 
> > Will sys.argv[1] return a valid path or just the filename?
> > If it just returns the filename, is there a simple way to get the path?
> > 
Here's the contents of my somescript.py:
---------------------------------
import sys
for index,arg in enumerate(sys.argv):
    print index, arg
-----------------------------------

Here is its output:

mu:python$ python somescript.py match.py
0 somescript.py
1 match.py

mu:python$ python somescript.py somescript.py stripaccents.py
0 somescript.py
1 somescript.py
2 stripaccents.py

mu:python$ python somescript.py Hello, how do you do?
0 somescript.py
1 Hello,
2 how
3 do
4 you
5 do?

mu:python$ python somescript.py /home/amoreira/public_html/index.php 
0 somescript.py
1 /home/amoreira/public_html/index.php

mu:python$ python somescript.py /unexistent/directory/unexistent_file.txt
0 somescript.py
1 /unexistent/directory/unexistent_file.txt

So, sys.argv has nothing to do with files or paths, it just stores whatever 
you write in the command line. I don't have a vista system on wich to try 
things, but I'm pretty sure it's the same.
 
> sysargv[1] returns the text following your script.
> 
> You can find the current working directory with this:
> 
> http://docs.python.org/library/os.html#os.getcwd

No. sys.argv[1:] (note the colon) does return (not quite "return", since it's 
not a function call but ok) the text following your script. sys.argv[1] only 
"returns" the *first* word after your script (in the invocation command)

Cheers
Ze Amoreira
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111101/7f4b412d/attachment.html>


More information about the Tutor mailing list