1

我在以下语句中随机收到 Python 中的编译器引发的“SyntaxError”异常:

with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
                                           ^
SyntaxError: invalid syntax

这里的 inputFileName 是来自我的构建环境的命令行参数,它应该在调用脚本之前创建并存在。下面是示例代码:

try:

with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
       print "do something"
except IOError as e: #(errno,strerror,filename):
        ## Control jumps directly to here if any of the above lines throws IOError.
        sys.stderr.write('problem with \'' + e.filename +'\'.')
        sys.stderr.write(' I/O error({0}): {1}'.format(e.errno, e.strerror) + '.' + '\n')
except:
    print "Unexpected error in generate_include_file() : ", sys.exc_info()[0]

我没有任何线索。请帮帮我。我正在使用python 2.7。(python27)

4

1 回答 1

4

分组with语句需要 Python 2.7 或更高版本。对于早期版本,嵌套语句:

with open(inputFileName, 'rU') as inputFile:
    with open(outputFileName,'w') as outputFile:

您收到的确切错误消息有力地证明了您在 Python 2.6而不是2.7 上运行代码:

$ python2.6
Python 2.6.8 (unknown, Apr 19 2012, 01:24:00) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
  File "<stdin>", line 1
    with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
                                               ^
SyntaxError: invalid syntax
>>>

$ python2.7
Python 2.7.3 (default, Oct 22 2012, 06:12:32) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
... 

您不能在任何withPython 版本中将语句与except处理程序分组,您需要在语句周围使用 a :try: except: with

try:
    with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
       print "do something"
except IOError as e: #(errno,strerror,filename):
    ## Control jumps directly to here if any of the above lines throws IOError.
    sys.stderr.write("problem with '{}'. ".format(e.filename))
    sys.stderr.write(' I/O error({0}): {1}.\n'.format(e.errno, e.strerror))
except:
    print "Unexpected error in generate_include_file() : ", sys.exc_info()[0]

除了我自己,我不会用毯子;毯子 except 也捕获名称、内存和键盘中断异常,您通常希望为此退出程序。

于 2013-04-09T09:46:01.463 回答