absl.flags Error: Trying to access flag before flags were parsed

Question:

I’m trying to parse this flag ‘dataroot’ (string type).

Consider this as a demo code:

from absl import flags
from absl.flags import FLAGS

flags.DEFINE_string('dataroot',"D:College",'path to root folder of dataset')


if __name__ == '__main__':

    #Hyperparameter
    # Root directory for dataset
    dataroot = FLAGS.dataroot

and this is what the error comes:

Traceback (most recent call last):
  File "d:/Github/cloned repo/Image-Restoration-in-Occluded-Images-using-GANs/main.py", line 49, in <module>
    dataroot = FLAGS.dataroot
  File "D:anacondalibsite-packagesabslflags_flagvalues.py", line 498, in __getattr__
    raise _exceptions.UnparsedFlagAccessError(error_message)
absl.flags._exceptions.UnparsedFlagAccessError: Trying to access flag --dataroot before flags were parsed.

Any idea where I’m going wrong?

Answers:

So, I solved this by doing this:

from absl import flags
from absl.flags import FLAGS

flags.DEFINE_string('dataroot',"D:College",'path to root folder of dataset')

def main(_argv):
    #Hyperparameter
    # Root directory for dataset
    dataroot = FLAGS.dataroot

if __name__ == '__main__':
    try:
        app.run(main)
    except SystemExit:
        pass
    

and this fixes the error..

Answered By: Prithviraj Kanaujia

You need to tell flags library to parse argv using FLAGS(sys.argv) before you can access FLAGS.xxx. Calling app.run() is a way to do that implicitly.

Example without app.run() by using explicit call to FLAGS(sys.argv):

  from absl import flags
  import sys
  flags.DEFINE_string('dataroot',"D:\College",'path to root folder of dataset')
  FLAGS = flags.FLAGS
  FLAGS(sys.argv)   # need to explicitly to tell flags library to parse argv before you can access FLAGS.xxx
  dataroot = FLAGS.dataroot
Answered By: Roland Pihlakas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.