bmpasini
bmpasini

Reputation: 1503

While loop doesn't stop

I have this simple code in Python:

import sys

class Crawler(object):

  def __init__(self, num_of_runs):
    self.run_number = 1
    self.num_of_runs = num_of_runs

  def single_run(self):
    #do stuff
    pass

  def run(self):
    while self.run_number <= self.num_of_runs:
      self.single_run()
      print self.run_number
      self.run_number += 1

if __name__ == "__main__":
  num_of_runs = sys.argv[1]
  crawler = Crawler(num_of_runs)
  crawler.run()

Then, I run it this way:

python path/crawler.py 10

From my understanding, it should loop 10 times and stop, right? Why it doesn't?

Upvotes: 6

Views: 3178

Answers (2)

Paco
Paco

Reputation: 4698

num_of_runs = sys.argv[1]

num_of_runs is a string at that stage.

while self.run_number <= self.num_of_runs:

You are comparing a string and an int here.

A simple way to fix this is to convert it to an int

num_of_runs = int(sysargv[1])

Another way to deal with this is to use argparser.

import argparse

parser = argparse.ArgumentParser(description='The program does bla and bla')
parser.add_argument(
    'my_int',
    type=int,
    help='an integer for the script'
)

args = parser.parse_args()
print args.my_int
print type(args.my_int)

Now if you execute the script like this:

./my_script.py 20

The output is:

20

Using argparser also gives you the -h option by default:

python my_script.py -h
usage: i.py [-h] my_int

The program does bla and bla

positional arguments:
  my_int      an integer for the script

optional arguments:
  -h, --help  show this help message and exit

For more information, have a look at the argparser documentation.

Note: The code I have used is from the argparser documentation, but has been slightly modified.

Upvotes: 12

Andy
Andy

Reputation: 50540

When accepting input from the command line, data is passed as a string. You need to convert this value to an int before you pass it to your Crawler class:

num_of_runs = int(sys.argv[1])

You can also utilize this to determine if the input is valid. If it doesn't convert to an int, it will throw an error.

Upvotes: 3

Related Questions