6

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?

asked Apr 30, 2015 at 14:39
2
  • 3
    10 is a string. You need to convert it to an int with the int() function. Commented Apr 30, 2015 at 14:41
  • 1
    See this for how Python handles comparisons between ints and strings stackoverflow.com/questions/3270680/… Commented Apr 30, 2015 at 14:43

2 Answers 2

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

answered Apr 30, 2015 at 14:42
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answered Apr 30, 2015 at 14:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.