[Tutor] Help with sys.argv
Dave Angel
davea at ieee.org
Fri Apr 29 12:47:16 CEST 2011
On 01/-10/-28163 02:59 PM, monkey415 at aim.com wrote:
> Hello,
>
> I am trying to learn how to use python with Facebook's Open Graph API. I am getting my feet wet with the following code authored by Matthew A. Russell. I copied it line for line for learning purposes, but I am getting the following error:
>
> Traceback (most recent call last):
> File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript
> exec codeObject in __main__.__dict__
> File "C:\Python27\Scripts\facebook__query.py", line 20, in<module>
> Q = sys.argv[1]
> IndexError: list index out of range
>
>
> Here is the code that this error is resulting from:
>
> #Querying the Open Graph for "programming" groups
>
> import sys
> import json
> import facebook
> import urllib2
> from facebook__login import login
>
> try:
> ACCESS_TOKEN = open('C:\Users\Jon\Documents\FacebookApps\facebook.access_token').read()
> except IOError, e:
> try:
> #Page 283 in Mining... for notes
> ACCESS_TOKEN = sys.argv[1]
> Q = sys.argv[2]
> except:
> print>> sys.stderr, \
> "Could not either find access token in 'C:\Users\Jon\Documents\FacebookApps\facebook.access_token' or parse args."
> ACCESS_TOKEN = login()
> Q = sys.argv[1]
>
> LIMIT = 100
>
> gapi = facebook.GraphAPI(ACCESS_TOKEN)
> ...
> ...
>
>
> Clearly this has something to do with sys.argv[1], and I think I'm getting an IOError somewhere along the line.
>
> I have tried quite hard to figure this out on my own using the Python tutorial, Google, and the book in which the code was found to no avail. Please help!
>
> Thanks,
> Jon
>
>
>
Usually, the first thing to do is to print sys.argv and see what it
looks like. If it has only one element in it, then you'd expect that
sys.argv[1] would give exactly that error. sys.argv[0] is the only
element.
Next, look up argv in the Python docs.
See http://docs.python.org/library/sys.html?highlight=argv#sys.argv
for a description. In particular, if you didn't pass any arguments to
the script, then argv will be of size 1, and you'll get the error you saw.
Fix is to add a check for len(sys.argv) to be greater than or equal to
however many arguments you need, and display an error and exit if not.
DaveA
More information about the Tutor
mailing list