在列表中运行一组Python脚本

Wal*_*mly 2 python

我正在开发一个Python项目,其中包含许多简单的示例脚本,以帮助新用户习惯系统.除了每个示例的源代码,我还包括我在测试计算机上获得的输出,以便用户知道一切顺利时会发生什么.

它发生在我身上,我可以用它作为单元测试的粗略形式.自动运行所有示例脚本,并针对预期输出执行大量差异.

我的所有示例脚本都以扩展名.py结尾,因此我可以轻松地使用类似的东西来获取文件名

pythonfiles=[filename for filename in os.listdir(source_directory) if filename[-3:]=='.py']
Run Code Online (Sandbox Code Playgroud)

因此,pythonfiles包含类似['example1.py','cool_example.py']等内容.

我可以使用什么语法来实际运行此列表中引用的脚本?

Mik*_*zur 8

您可以利用doctest帮助您完成此任务.编写一个执行每个脚本的方法,并在每个方法的docstring中粘贴预期的输出:

def run_example1():
    """
    This is example number 1. Running it should give you the following output:

    >>> run_example1()
    "This is the output from example1.py"
    """

    os.system('python example1.py') # or you could use subprocess here

if __name__ == "__main__":
    import doctest
    doctest.testmod()
Run Code Online (Sandbox Code Playgroud)

注意我没有测试过这个.

或者,正如Shane所提到的,您可以使用子流程.这样的东西会起作用:

import subprocess

cmd = ('example1.py', 'any', 'more', 'arguments')

expected_out = """Your expected output of the script"""

exampleP = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = exampleP.communicate() # out and err are stdout and stderr, respectively

if out != expected_out:
    print "Output does not match"
Run Code Online (Sandbox Code Playgroud)