目录
“Trying to access flag --gin_file before flags were parsed.”的解决办法:
gin配置参考文件的简单例子:
“Trying to access flag --gin_file before flags were parsed.”的解决办法:
程序参数配置都写在fileA.gin文件中,如下代码为test.py内容,
from absl import flags
import gin
flags.DEFINE_multi_string(
'gin_file', None, 'List of paths to the config files.')
flags.DEFINE_multi_string(
'gin_param', None, 'Newline separated list of Gin parameter bindings.')
FLAGS = flags.FLAGS
def main():
gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param)
if __name__ == "__main__":
main()
运行python?test.py --gin_file=fileA.gin,程序报错:
“absl.flags._exceptions.UnparsedFlagAccessError: Trying to access flag --gin_file before flags were parsed.”
解决办法:修改上述python代码:
from absl import flags
from absl import app
import gin
flags.DEFINE_multi_string(
'gin_file', None, 'List of paths to the config files.')
flags.DEFINE_multi_string(
'gin_param', None, 'Newline separated list of Gin parameter bindings.')
FLAGS = flags.FLAGS
def main(_argv):
gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param)
if __name__ == "__main__":
app.run(main)
再次运行python?test.py --gin_file=fileA.gin,就不再报错。
gin配置参考文件的简单例子:
首先编写fileA.py,fileA.gin,fileB.py三个文件并放在同一目录下,其中fileA.py为:
import gin
@gin.configurable
class Class_A():
def __init__(self, a=1, b=2, c=3):
self.a = a
self.b = b
self.c = c
def show_abc(self):
print("a=%d,b=%d,c=%d" %(self.a,self.b,self.c))
@gin.configurable
def test_fun(cla=Class_A()):
cla.show_abc()
if __name__=="__main__":
test_a = Class_A()
test_a.show_abc()
test_fun()
fileA.gin为:
import fileA
Class_A.a=4
Class_A.b=5
Class_A.c=6
fun/Class_A.a=10
fun/Class_A.b=11
fun/Class_A.c=12
template = @fun/Class_A()
test_fun.cla = %template
fileB.py为:
from absl import app
from absl import flags
import gin
from fileA import Class_A,test_fun
flags.DEFINE_multi_string(
'gin_file', None, 'List of paths to the config files.')
flags.DEFINE_multi_string(
'gin_param', None, 'Newline separated list of Gin parameter bindings.')
FLAGS = flags.FLAGS
def main(_argv):
gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param)
test_a=Class_A()
test_a.show_abc()
test_b=Class_A(7,8,9)
test_b.show_abc()
test_fun()
if __name__ == "__main__":
app.run(main)
运行python fileB.py --gin_file=fileA.gin,显示结果为:
a=4,b=5,c=6
a=7,b=8,c=9
a=10,b=11,c=12
若单独运行python fileA.py,显示结果为:
a=1,b=2,c=3
a=1,b=2,c=3
可以看出Class_A()实例的默认参数为a=1、b=2、c=3,test_fun()的默认参数为Class_A()默认初始化实例。在gin文件中,将Class_A()的参数a、b、c分别定义为4、5、6,则以该gin文件作为配置文件后,Class_A()实例的默认参数为a=4、b=5、c=6,如test_a;若在实例化Class_A()时自定义参数则不受gin文件影响,如test_b。若要修改test_fun()的参数Class_A()实例的参数取值,且取值不同于a=4、b=5、c=6,则可通过gin文件的范围界定机制来实现,如fun/Class_A.a=10就可以与Class_A.a=4区分开。当有大量参数需要配置或需要重复配置时,使用gin文件配置会更方便清晰。
参考链接:
python的gin库的介绍和使用
absl.flags Error: Trying to access flag before flags were parsed
|