Conditional import of modules in Python

后端 未结 3 519
北恋
北恋 2020-12-07 14:15

In my program I want to import simplejson or json based on whether the OS the user is on is Windows or Linux. I take the OS name as input from the user. Now, is it correct t

3条回答
  •  感动是毒
    2020-12-07 14:47

    I've seen this idiom used a lot, so you don't even have to do OS sniffing:

    try:
        import json
    except ImportError:
        import simplejson as json
    

提交回复
热议问题