Question

The Python interpreter can be started with -tt to raise a TabError exception if the interpreted file has inconsistent tab usage.

I'm trying to write a pre-commit hook for SVN that rejects files that raise this exception. I can pass the file being committed to python -tt but my problem is that the file is also executed, besides being checked. Is there a way to tell Python "just analyze the file, don't run it"? Or maybe some other approach would be better for accomplishing what I want.

Was it helpful?

Solution

You can do this using the py_compile module:

$ python -tt -c "import py_compile; py_compile.compile('test.py', doraise=True)"

The doraise=True will raise an exception and return with a nonzero exit code that you can easily test in your pre-commit hook.

OTHER TIPS

The preferred tab usage in Python is no tab usage at all (use four spaces for indentation). If that is your coding style then the problem may be reduced to checking if there are any tabs in the code. And this can be easily done with simple regexp, even with 'grep', so there is no even need to run the interpreter.

The 'py_compile' way have other advantage, though: it also checks Python code syntax, which may be desirable (though costs a bit of computation power of the SVN server).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top