Skip to main content
 首页 » 编程设计

python之使用 pep8 验证 python 语法时得到错误的输出

2024年10月17日6yjmyzz

我想使用 flake8 API 使用 pep8 模块验证 python 语法。为了验证,创建了字符串,其中包含要忽略的代码,稍后将在传递给函数以验证语法时将其转换为元组。

ignore_code = """ 
        'E101','E111','E112','E113','E114','E115', 
        'E116','E121','E122','E123','E124','E125', 
        """.replace("\n",' ') 
 
if flake8.main.check_file(fileName,ignore=tuple(ignore_code),complexity=-1): 
    return False 
else: 
    return True 

忽略 flake8.main.check_file 函数的关键字应该是

('E101','E111','E112','E113','E114','E115','E116','E121','E122','E123','E124','E125',) 

取而代之的是,

("'", 'E', '1', '0', '1', "'", ',', "'", 'E', '1', '1', '1', "'", ',', "'", 'E', '1', '1', '2', "'", ',', "'", 'E', '1', '1', '3', "'", ',', "'", 'E', '1', '1', '4', "'") 

如何通过忽略'\n'和额外空格将多行字符串转换为元组?

请您参考如下方法:

您的问题是,当您执行 tuple(ignore_code) 时,这就是您传入的内容。

>>> tuple(ignore_code) 
(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "'", 'E', '1', '0', '1', "'", ',', "'", 'E', '1', '1', '1', "'", ',', "'", 'E', '1', '1', '2', "'", ',', "'", 'E', '1', '1', '3', "'", ',', "'", 'E', '1', '1', '4', "'", ',', "'", 'E', '1', '1', '5', "'", ',', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "'", 'E', '1', '1', '6', "'", ',', "'", 'E', '1', '2', '1', "'", ',', "'", 'E', '1', '2', '2', "'", ',', "'", 'E', '1', '2', '3', "'", ',', "'", 'E', '1', '2', '4', "'", ',', "'", 'E', '1', '2', '5', "'", ',', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ') 

你基本上已经说了你需要做什么。

ignore keyword of flake8.main.check_file function should be ('E101','E111','E112','E113','E114','E115','E116','E121','E122','E123','E124','E125',)

你应该让 ignore_code 成为你想要传递的 iterable,IE

ignore_code = ('E101','E111','E112','E113','E114','E115','E116','E121','E122','E123','E124','E125') 
flake8.main.check_file(fileName, ignore=ignore_code, complexity=-1) 

如果您真的想要从该多行字符串中获得所需的结果,则需要对其进行格式化。执行 .replace("\n", "") 不会削减它,因为那里的空白字符比换行符多,而且您已经将内部项目括在引号中。此外,tuple(some_iterable) 生成可迭代项的元组。字符串是其字符的可迭代对象,但您需要一个可迭代对象,其项是 'E101' 之类的字符串而不是字符。

我能够通过以下方式获得您正在寻找的元组。

import ast 
the_tuple = tuple([ast.literal_eval(item.strip()) for item in ignore_code.split(",") if item.strip()]) 
#the_tuple 
#('E101', 'E111', 'E112', 'E113', 'E114', 'E115', 'E116', 'E121', 'E122', 'E123', 'E124', 'E125') 

详细说明该代码及其如何格式化多行字符串:

ignore_code.split(",") 会将字符串拆分成一个列表,其项目由由(但不包括) 分隔的字符串部分组成,字符。 IE ["\n 'E101'", "'E111'",#etc]

到此为止,但这些项目中仍然有空白。 item.strip() 将从字符串中删除前导和尾随空白字符,例如换行符、空格、制表符等。

现在您快完成了,但是项目看起来像这样 "'E101'", "'E111'", -- 它们是包含文字 '字符。要以您想要的方式解释这些,您可以使用 ast.literal_eval 对字符串进行文字评估,这会将 "'E101'" 评估为字符串 ' E101'

最后,有一项是空字符串(由于字符串中的尾随 ,)需要将其删除。因此条件 if item.split() 被添加到表达式中。

我们将这个想法放入生成器表达式中 [ast.literal_eval(item.strip()) for item in ignore_code.split(",") if item.strip()] 其中,英语,可以这样说

"Give me a list, whose items consist of ast.literal_eval(item.strip()) where item is every item from the list ignore_code.split(","), but only if the value of item.strip() is a non-empty string."