2

有没有办法:

  • 始终-t默认启用(警告标签使用不一致)
  • 能够在启动时以编程方式启用它(例如在sitecustomize.py模块中)

它也需要适用于嵌入式 Python(因此别名python或类似的解决方案将毫无用处)。使用sitecustomize.py允许我们连接到嵌入式 Python 实例,所以这似乎是一个适合它的地方。

我认为该warnings模块将提供一种打开此警告的方法,但我什么也没看到。

以供参考:

usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
...
-t     : issue warnings about inconsistent tab usage (-tt: issue errors)
...

关于如何做到这一点的任何建议?

谢谢。

4

2 回答 2

0

没有这样的选择。

你可以

  • 将解释器调用包装在 bash 脚本中
  • 定义别名
于 2013-01-22T16:13:52.657 回答
0

我能想到的唯一解决方案是导入钩子。虽然这有点超出了我希望做的事情,但我觉得这是我了解它们如何工作的一个很好的借口。

该解决方案不检查“不一致的空白”,它只检查制表符,但它很容易扩展。

结果如下:

import sys
import imp
import warnings


class TabCheckImporter(object):

    """Finder and loader class for checking for the presence of tabs

    """

    def find_module(self, fullname, path=None):
        """Module finding method

        """
        # Save the path so we know where to look in load_module
        self.path = path
        return self

    def load_module(self, name):
        """Module loading method.

        """
        # Check if it was already imported
        module = sys.modules.get(name)
        if module is not None:
            return module

        # Find the module and check for tabs
        file_, pathname, description = imp.find_module(name, self.path)
        try:
            content = file_.read()
            tab = content.find("\t")
            if tab > -1:
                lineno = content[:tab].count("\n") + 1
                warnings.warn_explicit(
                        "module '{0}' contains a tab character".format(name),
                        ImportWarning,
                        pathname,
                        lineno)
        except Exception as e:
            warnings.warn("Module '{0}' could not be checked".format(name),
                          ImportWarning)

        # Import the module
        try:
            module = imp.load_module(name, file_, pathname, description)
        finally:
            if file_:
                file_.close()

        sys.modules[name] = module
        return module


# Register the hook
sys.meta_path = (sys.meta_path or []) + [TabCheckImporter()]

# Enable ImportWarnings
warnings.simplefilter("always", ImportWarning)

导入此文件(替换->|为文字选项卡):

# File: test_tabbed.py
if True:
->| print "This line starts with a tab"

产生这个输出:

$ python -c 'import hook; import test_normal; import test_tabbed;'
test_tabbed.py:3: ImportWarning: module 'test_tabbed' contains a tab character
  print "This line starts with a tab"
于 2013-02-03T03:03:16.503 回答