Python - TypeError: argument of type 'NoneType' is not iterable

21,178

You get this error because you check if op contains the string "Not Registered", when op is actually None in runtime on the particular run that failed.

You should check whether op is None before you use it in the if and else clauses.

Something like this would handle this case:

if op is None:
    print "No operator"

if "Not Registered" in op:
    print "No Signal"
else:
    print "Operator Name: " + op
Share:
21,178
hillz
Author by

hillz

Updated on June 03, 2021

Comments

  • hillz
    hillz almost 3 years

    I'm new in python, so please bear with me. I wrote a script to check the carrier name on my 3G dongle with python-pyserial basically it looks like this:

    def get_operator():   
        ID_OPSEL=('51011:XL-Axiata','51010:Telkomsel','51089:Three','51001:Indosat','INDOSAT:Indosat','51008:Axis','TELKOMSEL:Telkomsel')
        if TYPE=="ZTE":
            resp=send_at_wait('AT+COPS?','+COPS:',3)
            if resp<>"TIMEOUT":
                resp=get_value(resp,'+COPS:')
                return resp.spilt('"')[1]
        else:    
            resp= send_at_wait("AT+COPS?; +COPS?\r","+COPS:",3)
            if resp<>"TIMEOUT":
                resp=get_value(resp,'+COPS:')
                resp=resp.split(',')
                if len(resp)>2: 
                    resp=resp[2].replace('"','')
                    for ln in ID_OPSEL:
                        if ln.find(resp)<>-1:
                            return ln.split(':')[1]
                else:
                    return "Not Registered"
    
    op=get_operator()
    if "Not Registered" in op:
        print "No Signal"
    else:
        print "Operator Name: " + op
    

    When there's a reception it all works fine but when there's no reciption the script returns:

    Traceback (most recent call last):
      File "/usr/bin/gsm", line 639, in <module>
        if "Not Registered" in op:
    TypeError: argument of type 'NoneType' is not iterable
    

    How do I fix it ?