简体   繁体   English

Linting .py文件在Python中加载时运行时

[英]Linting .py files run-time as they are loaded in Python

Does CPython interpreter provide any hooks to grab and inspect .py source files as they are being loaded? CPython解释器是否提供任何钩子来抓取和检查.py源文件在加载时?

I was thinking if PEP 666 http://www.python.org/dev/peps/pep-0666/ could be implemented with the existing interpreter. 我在想是否可以用现有的口译员实施PEP 666 http://www.python.org/dev/peps/pep-0666/ One could force additional source code syntax checks like tabs and spaces mix check there. 可以强制执行额外的源代码语法检查,例如制表符和空格混合检查。

I am well aware that the best practice is lint your source offline, but I am just playing with the idea to see if it is possible. 我很清楚,最好的做法是让你的源离线,但我只想玩这个想法,看看它是否可行。

Maybe the following helps you get started... 也许以下内容可以帮助您入门......

import sys
import os
import random


class GrammarNaziError(SyntaxError):
    pass


class GrammarNaziImporter(object):
    def find_module(self, module_name, package_path):
        if package_path:
            search_paths = package_path
            module_name = module_name.split('.')[-1]

        else:
            search_paths = sys.path + [ '.' ]

        for i in search_paths:
            path = os.path.join(i, module_name)
            if os.path.isdir(path):
                path = os.path.join(path, '__init__.py')
            else:
                path += '.py'

            if os.path.exists(path):
                if not self.valid_syntax(path):
                    raise GrammarNaziError(
                        "The module %s failed Grammar Nazi Inspection" % path)

                break

    def valid_syntax(self, path):
        return random.randint(0, 10) # substitute with logic of your choice

rest = GrammarNaziImporter()
sys.meta_path.insert(0, rest)

PS Good luck ;) PS祝你好运;)

PPS Edited so that the code works for init .py's and fails fast for found modules PPS编辑,以便代码适用于init .py,并且对于找到的模块快速失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM