简体   繁体   English

Python:防止模块导入时混合使用制表符/空格

[英]Python: prevent mixed tabs/spaces on module import

I know you can ensure pure tabbed/spaced code by calling Python with -tt . 我知道您可以通过使用-tt调用Python来确保纯制表-tt /空格代码。 However, when I have no control over the top-level call, can I still enforce this behaviour on the modules that are loaded by my script? 但是,当我无法控制顶级调用时,是否仍可以在脚本加载的模块上强制执行此行为?

If you have control about the initial script, then you can just add a check for it yourself. 如果您可以控制初始脚本,则可以自己添加一个检查。 For example, instead of just importing your student's script, you could have a function that first checks the module for indentation errors, and then imports it: 例如,不仅可以导入学生的脚本,还可以使用一个函数,该函数首先检查模块是否存在缩进错误, 然后将其导入:

# instead of
import foo
foo.bar()

# you have something like
foo = verifyAndImport('foo')
foo.bar()

And the verifyAndImport would look like this: 然后verifyAndImport看起来像这样:

import importlib
def verifyAndImport (moduleName):
    with open(moduleName + '.py') as f:
        # TODO: logic to verify consistent indentation

    return importlib.import_module(moduleName)

An alternative solution would be to have your initial script launch the actual script in a new Python process, with the -tt argument. 一种替代解决方案是让您的初始脚本使用-tt参数在新的Python进程中启动实际脚本。 But as tdelaney pointed out, this may cause errors that are not caused by your students. 但是,正如tdelaney指出的那样,这可能会导致不是您的学生引起的错误。

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

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