如何使用Python语言检查文件是否为Python文件

我正在开发一个Web应用程序,应聘者提交python代码,平台将其通过招聘者编写的单元测试传递。 我正在使用Django,但无法验证单元测试文件。 如何测试文件是否为python文件且格式正确(无语法或词法错误)?使用Python吗?

谢谢

评论
lenim
lenim

You can use the built-in function compile. Pass the content of the file as a string as the first param, file from which the code was read (If it wasn't read from a file, you can give a name yourself) as the second param and mode as the third.

尝试:

codeInString = open("full/file/path.py")
try:
    compile(codeInString.read(), 'your_code_name', 'exec')
except Exception as ex:
    print(ex)

如果测试文件的内容是:

print 1

将显示以下消息:

Missing parentheses in call to 'print'. Did you mean print(1)? (your_code_name, line 1)
点赞
评论