简体   繁体   中英

How to share a variable globally in python program?

I'm working on a program which has a config. I need to use a different config for the tests and the normal running of the program.

I manage all the software and tests using a manage.py script and all the tests are under python manage.py test ... (eg: python manage.py test all , python manage.py test db , ...)

To choose the config I did in the __init__.py of the config:

is_testing = sys.argv[1] == 'test'
if is_testing:
    from app.config.own import TestConfig as Config
else:
    from app.config.own import Config

and after I import the config from this file.

But sometime the test runner takes the first place in the argv so the test is in argv[2] or sometimes I run the tests by launching the script directly and not the manage.py .

My question is by which ways can I share a variable across the full codebase?

Thanks.

You could completely extract determining config from your config class and just have the script accept a CLI arg of the config path to execute. This would allow any config to be used.

python manage.py test --config=import.path.to.settings

Then you would have to map config to loadding the actual module. Django does this exact thing with their settings file, you could consult that for implementation details


Also I'd def recommend using argsparse , which would allow you to not have to deal with sys.argv[1] it provides type enforcement, documenation generation, positional and keyword arg support

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM