Python 2.7.3
From the console:
>>> try:
... fsock = open("something_that_does_not_exist")
... except IOError:
... print "The file does not exist"
... print "Let's keep going"
Traceback ( File "<interactive input>", line 5
print "Let's keep going"
^
SyntaxError: invalid syntax
If I save the same code into a script:
ex.py
def try1():
try:
fsock = open("something_that_does_not_exist")
except IOError:
print "The file does not exist"
print "Let's keep going"
and run it:
>>> import ex
>>> ex.try1()
The file does not exist
Let's keep going
>>>
I tried this on the console, IDLE and PythonWin. Same results.
What’s the difference?
EDIT:
I am learning Python with, among other sources, “Dive into Python” (http://www.diveintopython.net/). In example 6.1 the author shows exactly this example being run form the command line: http://www.diveintopython.net/file_handling/index.html
That’s why I thought this should work.
You have to finish the
tryexceptblock. If you add another line in between, the interpreter won’t mess up. The reason is it thinks the print statement is part of the try, which it isn’t. So if you finish the except statement, and let that part run and then paste the next print statement it will work.Then add this statement in:
Pasting into the python interpreter doesn’t always work for a bunch of reasons similar to this. The interpreter is meant for testing random snippets of code, and you cannot expect that pasting huge functions will always work when put in.
As you can see, this is the same thing: