0

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.

gogoer
  • 119
  • 1
  • 8
  • Start clang-format as subprocess, write code fragment to stdin of the subprocess, read formatted code fragment from stdout of the subprocess. Do I understand correctly that your question is how to start a subprocess from Python and how to access its stdin/stdout? – mkrieger1 Sep 05 '22 at 15:06
  • yes. If you can show me any relevant example, it will be great. – gogoer Sep 05 '22 at 15:40

0 Answers0