Python 2.7.3
从控制台:
>>> 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
如果我将相同的代码保存到脚本中:
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"
并运行它:
>>> import ex
>>> ex.try1()
The file does not exist
Let's keep going
>>>
我在控制台、IDLE 和 PythonWin 上试过这个。结果相同。
有什么不同?
编辑:
我正在学习 Python,其中包括“潜入 Python”(http://www.diveintopython.net/)。在示例 6.1 中,作者准确地展示了从命令行运行的示例: http ://www.diveintopython.net/file_handling/index.html
这就是为什么我认为这应该有效。