python:根据操作系统使用不同的功能 [英] python: use different function depending on os

查看:188
本文介绍了python:根据操作系统使用不同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个将在Linux和Solaris上执行的脚本。在两种操作系统上,大多数逻辑都是相同的,因此我只编写了一个脚本。但是由于某些部署的结构会有所不同(文件位置,文件格式,命令的语法),所以两个平台上的几个功能将有所不同。

I want to write a script that will execute on Linux and Solaris. Most of the logic will be identical on both OS, therefore I write just one script. But because some deployed structure will differ (file locations, file formats, syntax of commands), a couple of functions will be different on the two platforms.

这可以解决像

if 'linux' in sys.platform:
    result = do_stuff_linux()
if 'sun' in sys.platform:
    result = do_stuff_solaris()
more_stuf(result)
...

但是,在整个代码中撒些这些 ifs 似乎既麻烦又不礼貌。我也可以在一些 dict 中注册函数,然后通过dict调用函数。可能要好一些。

However it seems to cumbersome and unelegant to sprinkle these ifs throughout the code. Also I could register functions in some dict and then call functions via the dict. Probably a little nicer.

关于如何完成此操作的任何更好的想法?

Any better ideas on how this could be done?

推荐答案

解决方案1:

为每个需要复制并导入正确的功能的功能创建单独的文件:

You create separate files for each of the functions you need to duplicate and import the right one:

import sys
if 'linux' in sys.platform:
    from .linux import prepare, cook
elif 'sun' in sys.platform:
    from .sun import prepare, cook
else:
    raise RuntimeError("Unsupported operating system: {}".format(sys.platform))

dinner = prepare('pork')
drink_wine()
result = cook(dinner)

解决方案1.5:

如果您需要将所有内容保存在一个文件中,或只是不喜欢条件导入,您始终可以只为以下函数创建别名:

If you need to keep everything in a single file, or just don't like the conditional import, you can always just create aliases for the functions like so:

import sys

def prepare_linux(ingredient):
    ...

def prepare_sun(ingredient):
    ...

def cook_linux(meal):
    ...

def cook_sun(meal):
    ...

if 'linux' in sys.platform:
    prepare = prepare_linux
    cook = cook_linux
elif 'sun' in sys.platform:
    prepare = prepare_sun
    cook = cook_sun
else:
    raise RuntimeError("Unsupported operating system: {}".format(sys.platform))

dinner = prepare('chicken')
drink_wine()
result = cook(dinner)

这篇关于python:根据操作系统使用不同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆