簡體   English   中英

Python 2.x 到 3.x - Append 語法錯誤:如何使其與 Python 3.x 從 2.x 兼容。

[英]Python 2.x to 3.x - Append Syntaxerror: how to make it compatibale with Python 3.x from 2.x?

我有一個非常簡單的問題,我很難追查 - 這意味着一個非常簡單的答案。 在過去約 12 年左右的時間里,我在 python 2x 中編寫了大量腳本,我不得不移植到 python 3x。

經過搜索和許多、許多、許多修復后,我遇到了一個難以追蹤的更改。 我在如下所示的 e.append(lineno, line ) 中有語法錯誤。 關於如何改變它以使其與 python 3x 兼容的任何想法都將非常有用。

    self.__options = {}
    lineno = 0
    e = None                                  # None, or an exception
    while 1:
        line = fp.readline()
        if not line:
            break
        lineno = lineno + 1
        # skip blank lines
        if string.strip(line) == '':
            continue
        # skip lines starting with '['
        if line[0] == '[':
            continue
        # remove anything after '#'
        line = string.split(line, '#')[0]

        # key/value pairs can be seperated by whitespaces
        for opt in string.split(line):
            #if opt in string.whitespace:
            #    continue
            keyval = string.split(opt, '=')
            if len(keyval) == 2:
                self.__options[keyval[0]] = keyval[1]
            else:
                e = ParsingError(fpname)
                e.append(lineno, `line`)

    # if any parsing errors occurred, raise an exception
    if e:
        raise e

這是非常簡潔的歷史語法。

對於反引號,我建議您參考以下答案: https://stackoverflow.com/a/1673087/2988730 要點是反引號是調用repr的簡寫,直到它們在 python 3 中被刪除。它們在文檔中被稱為“轉換”操作:

代表(object repr

返回包含 object 的可打印表示的字符串。 這與轉換(反向引號)產生的值相同。 有時能夠像普通的 function 一樣訪問此操作很有用...

append 本身是正常的,盡管沒有記錄使用ParsingError.append方法:

def append(self, lineno, line):

從版本 3 開始, ConfigParser已重命名為configparser ,但仍然具有ParsingError.append方法。

因此,您需要進行一些更改:

  1. 在文件的開頭,將from ConfigParser import ParsingError更改為

    從 configparser 導入 ParsingError

  2. 將有錯誤的行更改為

    e.append(lineno, repr(line))

筆記

The multiple arguments to append evoke, but aren't related to, a behavior of list.append that hasn't been supported since python 2.0. 您可以在此處找到注釋: https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types 特別是腳注:

  1. Python 的 C 實現歷來接受多個參數並將它們隱式連接到一個元組中; 這不再適用於 Python 2.0。 自 Python 1.4 起,已棄用此錯誤功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM