从.py文件在文本文件上运行doctest?

时间:2012-08-16 18:07:32

标签: python visual-studio

我想在.txt文件上运行Python的doctest(即不在docstring上),但我不想转到命令行。

  

python -m doctest myfile.txt

我不想从命令行执行此操作的原因是我只是不想离开Visual Studio。我想用F5运行它,然后在VS中查看我的输出。

问题:如何从.py文件运行doctest,而不是从命令行运行?

1 个答案:

答案 0 :(得分:2)

结帐doctest.testfile。我想那会做你想要的......

以下是来自doctest.py的部分来源,例如用法:

def _test():
    testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
    if not testfiles:
        name = os.path.basename(sys.argv[0])
        if '__loader__' in globals():          # python -m
            name, _ = os.path.splitext(name)
        print("usage: {0} [-v] file ...".format(name))
        return 2
    for filename in testfiles:
        if filename.endswith(".py"):
            # It is a module -- insert its dir into sys.path and try to
            # import it. If it is part of a package, that possibly
            # won't work because of package imports.
            dirname, filename = os.path.split(filename)
            sys.path.insert(0, dirname)
            m = __import__(filename[:-3])
            del sys.path[0]
            failures, _ = testmod(m)
        else:
            failures, _ = testfile(filename, module_relative=False)
        if failures:
            return 1
    return 0


if __name__ == "__main__":
    sys.exit(_test())