开发者

Python: asserting that I'm running on POSIX?

I'm writing some POSIX-specific code, and although I'm not supporting other platforms I'd like to make sure they get a nice clear error at import time rather than strange errors, if they tried to use my code.

Is there a neat way to check that? I guess I could to an import po开发者_如何学运维six and catch the ImportError but that seems kind of verbose.


Take a look at os.name:

The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'.

There are also sys.platform and os.uname() if you require finer granularity.


you can:

def is_posix():
    try:
        import posix
        return True
    except ImportError:
        return False

You can also parse sys.platform or os.uname()[0], but I think it's more natural to ask "does your system has that feature" rather than "is you system one of ..., because I know they have that feature now".


instead of import posix you should import os, so you can have a subset of instruction available to the user (but not the posix specific ones) then you could use the sys.platform feature to check on which platform the user is running your code and then throw an exception or not :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜