tags:

views:

81

answers:

4

I'm currently going through a few tutorials to get myself up and running on Python, but I seem to hit the same problem a few times. The tutorial I'm currently following is Aloha.py in Introduction to Simulation by Norm Matloff.

The problem I'm hitting seems to be in the following code:

import random, sys
class node: # one object of this class models one network node
# some class variables
    s = int(sys.argv[1]) # number of nodes

The error message when I try and run the programme is:

Traceback (most recent call last):
  File "C:\Python26\Aloha.py", line 8, in <module>
    class node:
  File "C:\Python26\Aloha.py", line 10, in node
    s = int(sys.argv[0])
ValueError: invalid literal for int() with base 10: 'C:\\Python26\\Aloha.py'

I've worked out that sys.argv[1] doesn't exist when I try and run the program, so does anyone know where I might be going wrong? Is there some way of starting the program that will set these values or is my system somehow set up incorrectly?

+4  A: 

The traceback shows that you actually have this in your code:

s = int(sys.argv[0])

so you are referring to argument 0 - the script name itself - rather than 1.

Daniel Roseman
Good observation... the script name (as a string) sure won't evaluate as an integer.
ewall
True, I grabbed the wrong bit of text for the question. Should have been s = int(sys.argv[1])
Ian Turner
Note that Python's args are one off from what you might expect in two different ways. The argv for 'python Aloha.py 5' doesn't start with 'python', nor does it start with '5'. You'll get used to it though. :-)
Owen S.
@Ian: if you wrote sys.argv[1] the Python interpreter wouldn't have reported what you've posted. What does it _really_ say when you run it with sys.argv[1]?
Owen S.
I grabbed the wrong error message. It works when I add the options when running the programme.
Ian Turner
+3  A: 

sys.argv is for collecting the options given to the program on the command-line. So instead of just running the file, you'll want to run python aloha.py 5 (or whatever number you want).

(Otherwise, you could just set the number directly in the code instead of always expecting it on the command-line, as in s = 5 for example.)

ewall
+1  A: 

Also, to load in command line arguments when you run a program you'd want to run your program like this...

python Aloha.py 75

Where 75 is replaced by the number of nodes. 75 will then become argv[1].

Pace
A: 

try

s = int(sys.argv[-1])
Tumbleweed
This ain't a solution to his problem. His problem is that he does not understand what is happening! A one-liner does not help with that (and which is dubious anyway, because he probably forgets to give an argument on the command-line)
Peter Smit
But if he did, this is one way to get it. Not as good style as simply sys.argv[1] though.
Owen S.