tags:

views:

97

answers:

3

Hello,

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 to do the following

osys = raw_input("Press w for windows,l for linux")
if (osys == "w"):
    import json as simplejson
else:
    import simplejson  

Please help Thank You

+4  A: 

Perfectly correct, tons of packages do this. It's probably better to figure out the OS yourself instead of relying on the user; here's pySerial doing it as an example.

serial/__init__.py

import sys

if sys.platform == 'cli':
    from serialcli import *
else:
    import os
    # chose an implementation, depending on os
    if os.name == 'nt': #sys.platform == 'win32':
        from serialwin32 import *
    elif os.name == 'posix':
        from serialposix import *
    elif os.name == 'java':
        from serialjava import *
    else:
        raise Exception("Sorry: no implementation for your platform ('%s') available" % os.name)
Nick T
No, it's very incorrect to hardcode OS names to decide whether `simplejson` or `json` is available. You're quoting code from *inherently OS-specific* imports, which is a very different case. See Matt's answer for the correct approach.
Glenn Maynard
@Glenn Maynard: I'd defer to you then; I've never used the `json` package and was trying to answer the more general "can you do conditional imports of modules" question.
Nick T
A: 

Additionally you can do some automatization with imp module.

import imp
osys = raw_input("Press w for windows,l for linux")
jsonModules = {'w' : 'json', 'l' : 'simplejson'}
imp.load_module('json',*imp.find_module(jsonModules[osys]))
Odomontois
+9  A: 

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

try:
    import simplejson 
except:
    import json as simplejson
Matt Williamson
+1. We do it the opposite way: `import simplejson as json` because `json` is part of Python 2.6, where `simplejson` is an interim solution for previous releases.
S.Lott
Note that the official name for the module is json; the import alias should be inverted, eg. `import json` and `import simplejson as json`.
Glenn Maynard
Yup, updated accordingly
Matt Williamson