Ian Turner
Ian Turner

Reputation: 1413

Newbie Python question about sys.argv

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?

Upvotes: 0

Views: 5576

Answers (4)

shahjapan
shahjapan

Reputation: 14335

try

s = int(sys.argv[-1])

Upvotes: -1

Pace
Pace

Reputation: 43817

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].

Upvotes: 1

ewall
ewall

Reputation: 28110

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.)

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599610

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.

Upvotes: 4

Related Questions