python: use different function depending on os

前端 未结 2 1021
孤城傲影
孤城傲影 2021-01-21 05:17

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 str

2条回答
  •  走了就别回头了
    2021-01-21 06:13

    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)
    

提交回复
热议问题