0

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

这就是为什么我认为这应该有效。

4

1 回答 1

2

你必须完成这个try except块。如果您在两者之间添加另一行,解释器就不会搞砸。原因是它认为 print 语句是 try 的一部分,但事实并非如此。因此,如果您完成了 except 语句,并让该部分运行,然后粘贴下一个打印语句,它将起作用。

>>> try:
...     fsock = open("something_that_does_not_exist")
... except IOError:
...     print "The file does not exist"
...
<output is here>

然后将此语句添加到:

>>> print "Let's keep going"

出于与此类似的一系列原因,粘贴到 python 解释器中并不总是有效。解释器是用来测试随机代码片段的,你不能指望粘贴巨大的函数在插入时总是有效的。

如您所见,这是同一件事:

>>> try:
...     print 'hi'
... except:
...     print 'yo'
... print 'hi'
  File "<stdin>", line 5
    print 'hi'
        ^
SyntaxError: invalid syntax
>>> 
于 2013-02-03T04:16:11.390 回答