Python 中模块的条件导入

发布于 2024-09-14 18:13:45 字数 278 浏览 1 评论 0原文

在我的程序中,我想根据 Linux 或 Windows 操作系统导入 simplejsonjson 。我将操作系统名称作为用户的输入。现在,在这样的条件下这样做是否正确?

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

In my program I want to import simplejson or json based on OS being Linux or Windows. I take the OS name as input from the user. Now, is it correct to do it with a condition like this?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

盗心人 2024-09-21 18:13:45

我已经看到这个习惯用了很多,所以你甚至不需要做操作系统嗅探:

try:
    import json
except ImportError:
    import simplejson as json

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
往昔成烟 2024-09-21 18:13:45

要回答您的标题中的问题,而不是您提供的特定情况,这是完全正确的,大量的软件包都这样做。最好自己弄清楚操作系统,而不是依赖用户;这是 pySerial 做的一个例子。

serial/__init__.py

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
            )
        )

这应该仅在您假设并需要强有力保证某些接口/功能存在的情况下使用:例如名为 /dev/ 的“文件” ttyX。在您的情况下:处理 JSON,实际上没有任何特定于操作系统的内容,您只是检查包是否存在。在这种情况下,只需尝试导入它,如果失败则使用except回退:

try:
    import some_specific_json_module as json
except ImportError:
    import json

To answer the question in your title but 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.

serial/__init__.py

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 try to import it, and fall-back with an except if it fails:

try:
    import some_specific_json_module as json
except ImportError:
    import json
情定在深秋 2024-09-21 18:13:45

不建议使用 json 或 simplejson 与 OS 平台绑定。 simplejson 是 json 的更新和高级版本,因此我们应该首先尝试导入它。

基于 python 版本,您可以尝试以下方式导入 json 或 simplejson

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文