Search code examples
pythonpython-3.xpython-2.7clangclang-format

How to call clang-format from Python script


I have a Python tool that generates C++ files.

In order to test the tool, I have one test that compares the generated file with an expected output file.

diff = difflib.unified_diff(expectedFile.readlines(), file.readlines(), expectedFilename, filename)

The problem is that I'm getting some differences due to the format.

I can run clang-format on the expected output file. What I'm still trying to do is to run clang-format on the generated files, just before the difflib.unified_diff is called.

Can anyone help me on how I can run clang-format in Python on a file ?

Thank you very much!


Solution

  • You can use the call command that is supplied by Python to call an external command. For example, you can write a script like:

    #!/usr/bin/python
    import sys
    from subprocess import call
    lc = ["clang-format","test.c"] # replace 'test.c' with the your filename.
    retcode=call(lc)
    sys.exit(retcode);