Until the loop stops

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 like this:

python path/crawler.py 10

From my understanding, it should loop 10 times and stop, right? Why is this not so?

+6
source share
2 answers
 num_of_runs = sys.argv[1] 

num_of_runs is a string at this point.

 while self.run_number <= self.num_of_runs: 

You are comparing string and int here.

An easy way to fix this is to convert it to int

 num_of_runs = int(sysargv[1]) 

Another way to handle 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 run the script as follows:

 ./my_script.py 20 

Output:

20

Using argparser also provides 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 

See the argparser documentation for more information.

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

+12
source

When accepting input from the command line, data is transmitted as a string. You need to convert this value to int before passing it to the Crawler class:

 num_of_runs = int(sys.argv[1]) 

You can also use this to determine if an entry is valid. If it does not convert to int, it throws an error.

+3
source

Source: https://habr.com/ru/post/986306/


All Articles