Python 中模块的条件导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3496592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditional import of modules in Python
提问by Tim
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?
在我的程序中,我想根据用户所在的操作系统是 Windows 还是 Linux 导入 simplejson 或 json。我将操作系统名称作为用户的输入。现在,执行以下操作是否正确?
osys = raw_input("Press w for windows,l for linux")
if (osys == "w"):
import json as simplejson
else:
import simplejson
回答by Nick T
To answer the question in your titlebut not the particular case you provide, it's 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.
要回答标题中的问题而不是您提供的特定案例,这是完全正确的,大量软件包都这样做。最好自己弄清楚操作系统而不是依赖用户;这里以 pySerial 为例。
import sys
if sys.platform == 'cli':
from serial.serialcli import Serial
else:
import os
# chose an implementation, depending on os
if os.name == 'nt': # sys.platform == 'win32':
from serial.serialwin32 import Serial
elif os.name == 'posix':
from serial.serialposix import Serial, PosixPollSerial, VTIMESerial # noqa
elif os.name == 'java':
from serial.serialjava import Serial
else:
raise ImportError(
"Sorry: no implementation for your platform ('{}') available".format(
os.name
)
)
This should be only used in cases where you're assuming and need a strong guarantee that certain interfaces/features will be there: e.g. a 'file' called /dev/ttyX. In your case: dealing with JSON, there's nothing that is actually OS-specific and you are only checking if the package exists or not. In that case, just tryto import it, and fall-back with an exceptif it fails:
这应该仅在您假设并需要强有力地保证某些接口/功能将在那里的情况下使用:例如一个名为/dev/ttyX. 在您的情况下:处理 JSON,实际上没有任何特定于操作系统的内容,您只是在检查包是否存在。在这种情况下,只需try导入它,并except在失败时回退:
try:
import some_specific_json_module as json
except ImportError:
import json
回答by Matt Williamson
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
回答by Aashutosh jha
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.
不建议使用 json 或 simplejson 与 OS 平台绑定。simplejson 是 json 的更新和高级版本,所以我们应该先尝试导入它。
Based on python version you can try below way to import json or simplejson
基于python版本,您可以尝试以下方式导入json或simplejson
import sys
if sys.version_info > (2, 7):
import simplejson as json
else:
import json

