I know you can ensure pure tabbed/spaced code by calling Python with -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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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:
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. But as tdelaney pointed out, this may cause errors that are not caused by your students.