I have file whitch contains c++ code fragments. I want to make code fragments formatted. So I decide to make it with python script, but I can't find any examples. I Know how to find code fragment in file, but I dont understand how to format this fragment with clang-format. For example I have string
str = "if(i == 0){return;}"
How can I format it with clang-format?
In clang-format help I found:
If no arguments are specified, it formats the code from standard input and writes the result to the standard output.
How can I use this to format code fragment from script?
Update: after reading Python Popen sending to process on stdin, receiving on stdout I have
#!/usr/bin/env python
import subprocess
unformattedCode = 'void function(){}'
proc = subprocess.Popen('clang-format-12',stdout=subprocess.PIPE, stdin=subprocess.PIPE)
proc.stdin.write(unformattedCode.encode())
proc.stdin.close()
formattedCode = proc.stdout.read().decode()
print(formattedCode)
The main problem now that I have to close stdio stream after each write operation, to get formatted string. Without closing stdio there is no any data in stdout. As I have to process a lot of code fragments it is non-optimal to run new subprocess for each code fragment and then close it.