Calling from python script as function
raviapatel opened this issue · comments
Hi,
Thank you for this wonderful tool. Is there any way it can be called from within the python code with string as input and returns formatted string as output?
Right of the tip of hat, I'm not sure how to discern pressing enter
to confirm/close an input from pressing the same key to enter a line feed. But in principle, yes, fprettify
may be called from Python.
As a minimal example in Linux Debian 12/bookworm (branch testing), let us save the following snippet in file loop.f90
:
program test
implicit none
integer :: i
do i = 1, 5:
write (*, *) i
if (i .gt. 3) then
write ("i exceeds 3")
end if
end do
end program test
and the following Python program as loop_formatter.py
:
#!/bin/env python3
"""Example to call fprettify from Python."""
import argparse
import subprocess
def get_arguments():
"""Learn which file to process."""
parser = argparse.ArgumentParser(description="Call fprettify by Python.")
parser.add_argument("-f",
"--file",
metavar="file",
help="File to send to fprettify.")
args = parser.parse_args()
data = args.file
return data
def main():
"""Perform the work."""
file = get_arguments()
# output to the CLI by flag -s (default: false)
command = str(f"fprettify {file} -s")
subprocess.call(command, shell=True)
if __name__ == "__main__":
main()
After provision of the executable bit (chmod u+x loop_formatter.py
), the call
./loop_formater.py -f loop.f90
offers the same output (to the CLI) as
fprettify -s loop.f90
Yes the i am already aware of using subprocess I was more looking in terms of intergrating it with a code generator. So what I would like is to input string as get string as output something like....
def (instr, fprettifyOptions):
....
return fromattedStr