Search code examples
pythonglobal-variablesargparse

in python, how to make main args global


I want to access the args values in a class function in python.
For example, I wrote a sample test program below.

#!/usr/bin/env python

import argparse

class Weather(object):
    def __init__(self):
        self.value = 0.0
    def run(self):
        print('in weather.run')
        if (args.sunny == True):
            print('It\'s Sunny')
        else:
            print('It\'s Not Sunny')

def main():
    argparser = argparse.ArgumentParser(
        description=__doc__)
    argparser.add_argument(
        '--sunny', action='store_true', dest='sunny', help='set if you want sunny weather')
    args = argparser.parse_args()

    print('args.sunny = ', args.sunny)

    weather = Weather()


    weather.run()

if __name__ == '__main__':
    main()

When I run it(./test.py), I get errors below.

('args.sunny = ', False)
in weather.run
Traceback (most recent call last):
  File "./test.py", line 30, in <module>
    main()
  File "./test.py", line 27, in main
    weather.run()
  File "./test.py", line 10, in run
    if (args.sunny == True):
NameError: global name 'args' is not defined

I tried putting 'global args' in the Weather.run function but got the same error. What is the correct method?


Solution

  • You can set it global by:

    global args
    args = argparser.parse_args()
    

    or just pass sunny as argument to weather:

    def run(self, sunny):
    .....
    
    weather.run(self, args.sunny)