Fortran代码格式化工具fprettify
作为程序员,可能读代码的时间要比写代码的时间还要长。在你不得不阅读那些“没有缩进、嵌套分支代码太长不能确定对应的代码段等”糟心代码时,可能一款格式化工具能够帮助你抚平暴怒的心情。
fprettify
就是一款针对Fortran项目代码的自动化格式工具。
项目地址:https://github.com/pseewald/fprettify
安装
fpretty是基于Python开发的脚本工具,依赖Python3 (最新版本不再支持Python 2.7)。
使用pip
或者conda
安装即可。
$ pip install --upgrade fprettify
#or
$ conda install -c conda-forge fprettify
使用
查看fprettify
选项说明
$ fprettify -h
常用选项
-i INDENT, --indent INDENT
相对缩进宽度,默认是3个空格
-l LINE_LENGTH, --line-length LINE_LENGTH
每行最多列数(默认132列)
-w {0,1,2,3,4}, --whitespace {0,1,2,3,4}
控制插入白空格范围,
- 0 : 最低限度的空格
- 1:操作符(除了算术操作符
+-*/
等)、print/read插入空格 - 2:操作符、print/read、+/-
- 3: 操作符、print/read、
+/-/*/\
- 4: 操作符、print/read、
+/-/*/\
,type component selector
--whitespace-*
布尔值,打开/关闭具体语法的白空格,默认是None。对-w
的细分补充,具体选项见说明。
--c-relations
C风格的关系操作符(<, <=,...
)
-d, --diff
不对文件修改,而是将格式化前后内容差异diff输出到stdout
-s, --stdout
格式化内容输出到stdout,而不是在源文件直接修改。
-S, --silent, --no-report-errors
即使格式化时发生警告或者错误,也不输出到stderr
,默认是False。
-r, --recursive
递归格式化所有Fortran文件,默认False
-e EXCLUDE, --exclude EXCLUDE
排除指定文件或目录不做格式化。
-f FORTRAN, --fortran FORTRAN
-r
选项递归搜索后缀名为.f, .for, .ftn, .f90, .f95, .f03, .fpp,.F, .FOR, .FTN, .F90, .F95, .F03, .FPP
的Fortran源代码文件,使用-f
选项可以重置默认的Fortran源代码文件后缀,指定多个后缀名需要重复-f
选项。
-c CONFIG_FILE, --config-fiel CONFIG_FILE
如果需要经常使用格式化工具,且有多个选项组合,可以使用-c
配置文件方式。该功能依赖ConfigArgParse
模块,配置文件语法说明见:https://pypi.org/project/ConfigArgParse/
使用示例
Fortran源代码文件:
program demo
integer :: endif,if,elseif
integer,DIMENSION(2) :: function
endif=3;if=2
if(endif==2)then
endif=5
elseif=if+4*(endif+&
2**10)
elseif(endif==3)then
function(if)=endif/elseif
print*,endif
endif
end program
- 默认配置
fprettify test.F90
program demo
integer :: endif, if, elseif
integer, DIMENSION(2) :: function
endif = 3; if = 2
if (endif == 2) then
endif = 5
elseif = if + 4*(endif + &
2**10)
elseif (endif == 3) then
function(if) = endif/elseif
print *, endif
end if
end program
- 缩进2个空格、指定白空格插入范围
$ fprettify -i 2 -w 4 test.F90
格式化后代码如下:
program demo
integer :: endif, if, elseif
integer, DIMENSION(2) :: function
endif = 3; if = 2
if (endif == 2) then
endif = 5
elseif = if + 4 * (endif + &
2**10)
elseif (endif == 3) then
function(if) = endif / elseif
print *, endif
end if
end program
可以控制-w
查看不同数值对代码的影响。
建议
- 如果要在其他人"Bad code"基础上继续开发,尝试先使用
fprettify
工具。 - 如果自己写代码时未按照约定的代码风格指南,提交代码前使用
fprettify
格式化代码。

