python: use different function depending on os

烈酒焚心 提交于 2020-06-09 02:55:11

问题


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.

This could be dealt with like

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

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:


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

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



回答2:


You can do it like this:

if 'linux' in sys.platform:
    def do_stuff():
        result = # do linux stuff
        more_stuff(result)
elif 'sun' in sys.platform:
    def do_stuff():
        result = # do solaris stuff
        more_stuff(result)

And then simply call do_stuff().



来源:https://stackoverflow.com/questions/43540782/python-use-different-function-depending-on-os

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!