James Jeffery
James Jeffery

Reputation: 12599

Can't break out of Python loop

I'm having problems breaking out of a loop in Python. It just won't break out.

Here is dl.py:

#! /usr/bin/python
import urllib
import urllib2
import os
import sys
import re 
from pyquery import PyQuery as pq

url = sys.argv[1]
limit = sys.argv[2]

count = 0

while True :
    if count >= limit :
        break
    print 1;
    count += 1

print 'Complete ... exiting';

It just loops forever, I can't understand why. Python is not my native language, I'm using it to code some shell scripts.

I run it like so ./dl.py http://url.com 3

What am I doing wrong?

Upvotes: 1

Views: 601

Answers (4)

Kasravnd
Kasravnd

Reputation: 107347

You can invoke sys.argv just one time when you are many arg and use int for limit because the sys.argv get string from input :

 user_args = sys.argv[1:]
 url, limit = user_args
 limit=int(limit)

Upvotes: 0

Alex Riley
Alex Riley

Reputation: 177018

You need to convert limit to an integer using int(limit) (else it will be treated as a string by Python when read from the command line). Integers are evaluated to be less than strings (at least in Python 2).

>>> int < str
True

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 48028

You need to convert limit to an integer using int(limit). In Python 2.x 3 > '2' will always return False so your loop never completes.

Upvotes: 6

Pedro Werneck
Pedro Werneck

Reputation: 41928

The problem is that sys.argv[2] will return a string, and when you compare a string with an integer in Python, the string is always greater. Try using if count >= int(limit): instead.

Upvotes: 0

Related Questions