Conditional import of modules in Python

后端 未结 3 516
北恋
北恋 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 15:03

    It is not advisable to use to bind json or simplejson with OS platform. simplejson is newer and advanced version of json so we should try to import it first.

    Based on python version you can try below way to import json or simplejson

    import sys
    if sys.version_info > (2, 7):
        import simplejson as json
    else:
        import json
    

提交回复
热议问题