Exception handling for socket.error in Python 3.5/RStudio

Martin A. Brown martin at linux-ip.net
Fri Feb 5 15:44:15 EST 2016


Hi there Shaunak,

I saw your few replies to my (and Nathan's) quick identification of 
syntax error.  More comments follow, here.

>I am running this python script on R-studio. I have Python 3.5 installed on my system.
>
>count = 10
>while (count > 0):
>    try :
>        # read line from file:
>        print(file.readline())
>        # parse
>        parse_json(file.readline())
>        count = count - 1
>    except socket.error as e
>        print('Connection fail', e)
>        print(traceback.format_exc())
>
># wait for user input to end
># input("\n Press Enter to exit...");
># close the SSLSocket, will also close the underlying socket
>ssl_sock.close()
>
>The error I am getting is here:
>
>line 53 except socket.error as e ^ SyntaxError: invalid syntax
>
>I tried changing socket.error to ConnectionRefusedError. and still got the same error.

We were assuming that line 53 in your file is the part you pasted 
above.  That clearly shows a syntax error (the missing colon).

If, after fixing that error, you are still seeing errors, then the 
probable explanations are:

  * you are not executing the same file you are editing

  * there is a separate syntax error elsewhere in the file (you sent
    us only a fragment)

Additional points:

  * While the word 'file' is not reserved in Python 3.x, it is in 
    Python 2.x, so, just be careful when working with older Python 
    versions.  You could always change your variable name, but you 
    do not need to.

  * When you catch the error in the above, you print the traceback 
    information, but your loop will continue.  Is that what you 
    desired?

I might suggest saving your work carefully and make sure that you 
are running the same code that you are working on.  Then, if you 
are still experiencing syntax errors, study the lines that the 
interpreter is complaining about.  And, of course, send the list an 
email.

Best of luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Python-list mailing list