try... except SyntaxError: unexpected EOF while parsing

Steve Holden steve at holdenweb.com
Wed Apr 4 13:55:11 EDT 2007


oscartheduck wrote:
> I have a small script for doing some ssh stuff for me. I could have
> written it as shell script, but wanted to improve my python skills
> some.
> 
> RIght now, I'm not catching a syntax error as I'd like to.
> 
> Here's my code:
> 
> #!/usr/bin/env python
> import sys
> import os
> 
> port = input("Please enter a port to connect on. If you're unsure or
> just want the default of port 2024 just hit enter  --  ")
> 
> 
> try:
>   if port > 65535:
>     print "That's not a valid port number, sorry. Between 0 and 65535
> is cool."
>     sys.exit()
>   else:
>     cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port
> except SyntaxError:
>       cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"'
> 
> os.system(cmd)
> 
> 
> I'm under the impression that the except should catch the syntax error
> and execute the "default" command, but hitting enter at the input
> value doesn't lead to that. Any ideas what's going wrong?
> 
Yes. SyntaxError is raised when the interpreter is compiling the Python 
into byetcodes ready for execution. This *can* happen at run time, but 
usually it's when you are importing a module and so it gets 
transmogrified into an ImportError, though you can trigger it with, for 
example, eval:

  >>> eval("print < m s q")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<string>", line 1
     print < m s q
         ^
SyntaxError: invalid syntax
  >>>

However, if you run your program and give it an invalid port number 
surely the resulting traceback would *tell* you what exception you need 
to trap if you used a %d substituion rather than a %s. Since pretty much 
anything is valid for a %s substitution the problem is that you will be 
calling os.system() on a command with a non-numeric port number and not 
catching the resulting exception.

Using input(), by the way, is a recipe for disaster with non-trustworthy 
users. I'd much prefer to use raw_input() and convert explicitly to integer.

The easiest way to proceed would then be to perform sensible error 
checking on the port number before proceeding:

port = raw_input("Port # (enter for 2204 default: ")
if port == "":
     port = 2204
try:
     port = int(port)
except ValueError:
     raise ValueError("Port number must be numeric")

or something like that. Really you should be in a loop which terminated 
when you get an acceptable port number.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list