Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Chan Kim Avatar asked Nov 15 '19 08:11

Chan Kim


2 Answers

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)
like image 104
Ramon Medeiros Avatar answered Oct 02 '22 06:10

Ramon Medeiros


Why don't you add whatever is in main() into the if statement?

#!/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')

if __name__ == '__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()
like image 45
Maarten-vd-Sande Avatar answered Oct 02 '22 08:10

Maarten-vd-Sande