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.7ではなくPython 2.6 でコードを実行しているという強力な証拠です。

$ 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:
... 

Pythonのどのバージョンでも、ハンドラーを使用してwithステートメントをグループ化することはできません。代わりに、ステートメントの前後にa を使用する必要があります。excepttry: 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 に答える