如何在异常/错误后继续在Python中继续执行程序

时间:2020-12-20 21:46:41

标签: python-3.x testing exception

我是python编程的老师。我给我的学生布置了一些家庭作业,现在我必须纠正它们。作业作为函数提交。这样,我就可以使用 importlib 的导入模块来导入每个学生写的函数。我已将所有测试放在 try/except 块中,但是当学生做错事(即要求用户输入、错误缩进等)时,主测试程序挂起或停止。

有没有一种方法可以在不让主程序因为学生的错误而停止的情况下执行所有测试?

提前致谢。

1 个答案:

答案 0 :(得分:0)

Python 在两遍中查找错误。

第一遍在执行一行代码之前很久就捕获了错误。

第二遍只会在运行时发现错误。

try-except 块不会捕获错误的缩进。

try:
    x = 5
    for x in range(0, 9):
    y = 22
    if y > 4:
    z = 6
except:
    pass

你会得到类似的东西:

File "D:/python_sandbox/sdfgsdfgdf.py", line 6
    y = 22
    ^
IndentationError: expected an indented block

您可以使用 exec 函数执行存储在字符串中的代码。

with open("test_file.py", mode='r') as student_file:
    lines = student_file.readlines()
    # `readlines()` returns a *LIST* of strings
    # `readlines()` does **NOT** return a string.
    big_string = "\n".join(lines)
    try:
        exec(big_string)
    except BaseException as exc:
        print(type(exc), exc)

如果使用 exec,程序不会因缩进错误而挂起。
exec 非常危险。

学生可以使用以下代码删除一个或多个硬盘驱动器上的所有文件:

import os
import shutil
import pathlib

cwd_string = os.getcwd()
cwd_path = pathlib.Path(cwd_string)
cwd_root = cwd_path.parts[0]

def keep_going(*args):
    # keep_going(function, path, excinfo)
    args = list(args)
    for idx, arg in enumerate(args):
        args[idx] = repr(str(arg))
    spacer = "\n" + 80*"#" + "\n"
    spacer.join(args)

shutil.rmtree(cwd_root, ignore_errors=True, onerror=keep_going)

您正在尝试执行的操作称为“单元测试

单元测试有一个python library

理想情况下,您将使用“测试环境”来防止损坏您自己的计算机。

我建议您购买可以在互联网(eBay 等)上找到的最便宜的二手笔记本电脑。确保有笔记本电脑工作的照片(减去电池。也许让笔记本电脑一直插着电源。

使用便宜的笔记本电脑测试学生的代码。

您可以覆盖内置的 input 函数。
这样可以防止程序挂起...

编写良好的测试环境还可以轻松重定向命令行输入。

def input(*args, **kwargs):
    return str(4)

def get_user_input(tipe):
    prompt = "please type in a(n) " + str(tipe) + ":\n"
    while True:
        ugly_user_input = input(prompt)
        pretty_user_input = str(ugly_user_input).strip()
        try:
            ihnt = int(pretty_user_input)
            return ihnt
        except BaseException as exc:
            print(type(exc))
            print("that's not a " + str(tipe))

get_user_input(int)
相关问题