【问题标题】:how to use exclude option with pep8.py如何在 pep8.py 中使用排除选项
【发布时间】:2011-08-17 11:17:00
【问题描述】:

我有这样的目录结构

/path/to/dir/a/foo
/path/to/dir/b/foo

并且想要在目录/path/to/dir/ 上运行 pep8,不包括/path/to/dir/a/foo

pep8 --exclude='/path/to/dir/a/foo' /path/to/dir

pep8 的预期输出是,它不应该包含来自/a/foo/ 的文件

但 pep8 也在检查 /a/foo/ 中的文件

当我这样做时

pep8 --exclude='foo' /path/to/dir

它不包括来自a/foo/b/foo/的文件

pep8 exclude 选项的模式是什么,以便它仅从/a/foo/ 中排除文件,而不是从b/foo/ 中排除文件?

【问题讨论】:

    标签: python pep8


    【解决方案1】:

    我确定我在这里重新发明轮子,但我也无法让 API 正常工作:

    import os
    import re
    from pep8 import StyleGuide
    
    
    def get_pyfiles(directory=None, exclusions=None, ftype='.py'):
        '''generator of all ftype files in all subdirectories.
        if directory is None, will look in current directory.
        exclusions should be a regular expression.
    
        '''
        if directory is None:
            directory = os.getcwd()
    
        pyfiles = (os.path.join(dpath, fname)
                   for dpath, dnames, fnames in os.walk(directory)
                   for fname in [f for f in fnames
                                 if f.endswith(ftype)])
    
        if exclusions is not None:
            c = re.compile(exclusions)
            pyfiles = (fname for fname in pyfiles if c.match(fname) is None)
    
        return pyfiles
    
    
    def get_pep8_counter(directory=None, exclusions=None):
        if directory is None:
            directory = os.getcwd()
        paths = list(get_pyfiles(directory=directory, exclusions=exclusions))
        # I am only interested in counters (but you could do something else)
        return StyleGuide(paths=paths).check_files().counters
    
    counter = get_pep8_counter(exclusions='.*src.*|.*doc.*')
    

    【讨论】:

    • 我想实际上我只是不了解 unix 正则表达式 (?) 并想使用 Python 自己的正则表达式。
    【解决方案2】:

    你可以试试这样的:

    pep8 --exclude='*/a/foo*' /path/to/dir
    

    排除部分使用 fnmatch 来匹配 source code 中看到的路径。

    def excluded(filename):
        """
        Check if options.exclude contains a pattern that matches filename.
        """
        basename = os.path.basename(filename)
        for pattern in options.exclude:
            if fnmatch(basename, pattern):
                # print basename, 'excluded because it matches', pattern
                return True
    

    【讨论】:

    • 我认为你现在必须使用 pycodestyle 否则你会收到警告。我用pycodestyle --max-line-length=120 --exclude='*/migrations'
    猜你喜欢
    • 2010-09-28
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多