Adel Bouhraoua
Adel Bouhraoua

Reputation: 71

How to check if a file is a Python file in Python language

I'm working on a web application where candidates submit python code and the platform passes them through a unit test which is written by the recruiters. I'm using Django and I'm having trouble validating the unit-test file. How to test if a file is a python file and that it's correctly formed (no Syntax or lexical errors)? using Python ?

Thanks

Upvotes: 1

Views: 54

Answers (1)

Gabio
Gabio

Reputation: 9504

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.

Try:

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

In case the content of the test file is:

print 1

The compile function will throw a SyntaxError and the following message will be printed:

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

Upvotes: 2

Related Questions