在 python 中,如何使 main args 全局化

Cha*_*Kim 5 python global-variables argparse

我想访问 python 类函数中的 args 值。
例如,我在下面编写了一个示例测试程序。

#!/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()
Run Code Online (Sandbox Code Playgroud)

当我运行它(./test.py)时,出现以下错误。

('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
Run Code Online (Sandbox Code Playgroud)

我尝试将“全局参数”放在 Weather.run 函数中,但得到了同样的错误。正确的方法是什么?

Ram*_*ros 5

您可以通过以下方式将其设置为全局:

global args
args = argparser.parse_args()
Run Code Online (Sandbox Code Playgroud)

或者只是将晴天作为天气的参数:

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

weather.run(self, args.sunny)
Run Code Online (Sandbox Code Playgroud)