我想编写一个将在 Linux 和 Solaris 上执行的脚本。大多数逻辑在两个操作系统上都是相同的,因此我只写了一个脚本。但是由于某些部署的结构会有所不同(文件位置、文件格式、命令语法),因此两个平台上的一些功能会有所不同。
这可以这样处理
if 'linux' in sys.platform:
result = do_stuff_linux()
if 'sun' in sys.platform:
result = do_stuff_solaris()
more_stuf(result)
...
然而,在整个代码中散布这些 ifs
似乎既麻烦又不雅观。我也可以在一些 dict
中注册函数,然后通过字典调用函数。可能会好一点。
关于如何做到这一点有更好的想法吗?
最佳答案
解决方案一:
您为每个需要复制和导入正确的函数创建单独的文件:
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:
如果您需要将所有内容保存在一个文件中,或者只是不喜欢条件导入,您总是可以像这样为函数创建别名:
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:根据操作系统使用不同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43540782/