473,795 Members | 2,974 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

try... except SyntaxError: unexpected EOF while parsing

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?

Apr 4 '07 #1
7 9889
On Apr 4, 12:38 pm, "oscarthedu ck" <oscarthed...@g mail.comwrote:
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?
Try sticking your

port = input("Please enter a port to connect on. If you're unsure or
just want the default of port 2024 just hit enter -- ")

inside your "try" block instead. Or switch to using the "raw_input"
builtin instead of "input".

Mike

Apr 4 '07 #2

"oscarthedu ck" <os**********@g mail.comwrote in message
news:11******** **************@ e65g2000hsc.goo glegroups.com.. .
|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?

Try putting the input statement after the try statement.

Apr 4 '07 #3
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("Por t 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

Apr 4 '07 #4
(Are you Howard the Duck's lesser known cousin?)
>>>>"oscar" == oscartheduck <os**********@g mail.comwrites:
oscarI have a small script for doing some ssh stuff for me. I could
oscarhave written it as shell script, but wanted to improve my python
oscarskills some.

oscarRIght now, I'm not catching a syntax error as I'd like to.

Well, you should probably never catch SyntaxError (unless you use exec or
eval, both of which you should also probably never use), however... What
you're describing is not a Python syntax error. In addition, if you're
expecting to catch problems with the call to input("Please ...") you'll need
to have it within the try block.

Given that port numbers have to be ints I'd try something like:

port = 2024
userport = raw_input("Plea se enter a port #: ").strip()
if userport:
try:
port = int(userport)
except ValueError:
pass
if port 65535:
blah blah blah
...

Note that input("prompt") is equivalent to eval(raw_input( "prompt")), so you
should probably never use it. (It's going away in Python 3.0 anyway.)

Skip
Apr 4 '07 #5
On 4 Apr 2007 10:38:24 -0700, oscartheduck <os**********@g mail.comwrote:
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.
....
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:
....
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?
You didn't include the full exception that you're getting, but my
guess is that the line trowing the error is the one calling input().
Move your try up before that line, and it should work as you expected.

On a slightly different note, input() isn't really the right function
to call here. input() evaluates python commands. Instead, use
raw_input() which just returns a user-entered string.

Something like this (untested):
sshport = raw_input('Port : ')
if sshport == "":
sshport = "2024"
try:
sshport = int(sshport)
except ValueError:
print "Not a valid port"
sys.exit()

cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port
--
Jerry
Apr 4 '07 #6
Wow. Thanks, everyone, for the responses. It helps a lot having such a
well informed and helpful resource.

Apr 4 '07 #7
Steve Holden wrote:
oscartheduck wrote:
[...]
>>
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:
Of course I omitted to notice that input() can also raise SyntaxError
.... sorry about that.

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

Apr 4 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1547
by: John J. Lee | last post by:
Bare "except:", with no exception specified, is nasty because it can easily hide bugs. There is a case where it seemed useful to me in the past. Now it seems like a bad idea to me (but I think I might still be confused about it, hence this post). It's this: When you're processing a input from a file-like object connected to an external source like a network connection, disk file etc, you have to expect broken, and often malicious,...
4
11999
by: sunil | last post by:
I am creating a XML document which opens fine in IE. Implies MSXML thinks it is a well formed document. But when I try to load this document in VB.net using the following code Dim doc As New XmlDocument doc.Load("C:\Projects\SQLXML\corc.xml") I get the following error: "System.Xml.XmlException: An unexpected end of file parsing CDATA has
2
1956
by: wawork | last post by:
Fairly new to python. In a try except how do you display the true (raw) error message so it can be displayed back to the user?
32
4421
by: Rene Pijlman | last post by:
One of the things I dislike about Java is the need to declare exceptions as part of an interface or class definition. But perhaps Java got this right... I've writen an application that uses urllib2, urlparse, robotparser and some other modules in the battery pack. One day my app failed with an urllib2.HTTPError. So I catch that. But then I get a urllib2.URLError, so I catch that too. The next day, it encounters a urllib2.HTTPError, then...
3
3320
by: Anup Daware | last post by:
Hi Group, I am facing a strange problem here: I am trying to read xml response from a servlet using XmlTextWriter. I am able to read the read half of the xml and suddenly an exception: “Unexpected end of file while parsing Name has occurred” isbeing thrown. Following is the part o xml I am trying to read: <CHECK_ITEM_OUT>
5
1813
by: Nebur | last post by:
I'm using the contract.py library, running Python 2.4.4. Now I'm confronted with the following exception backtrace: (...) File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in _check_preconditions p = f.__assert_pre AttributeError: 'function' object has no attribute '__assert_pre' For my surprise, I found that the code of contract.py around line 1265
5
7345
by: Ed Jensen | last post by:
I'm using: Python 2.3.2 (#1, Oct 17 2003, 19:06:15) on sunos5 And I'm trying to execute: #! /usr/bin/env python try:
20
3171
by: Jim Michaels | last post by:
I have a 638 line glob of PHP code & HTML that won't run. I get "PHP Parse error: syntax error, unexpected '}' in quiz\\quiz.php on line 594". I wrote a brace checker that checks perens, square brackets, and curly braces for mismatches & opens and it checks out perfect. so I don't know what it is about the curly brace error. it's false. anybody have a clue as to what the real error might be? the code looks pristine to me. ...
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10215
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.