如何编写 Python 代码以支持 Windows 和 Linux?

Sqr*_*tPi 1 python linux windows

我有一些代码需要在 Windows 和 Linux 上做非常相似的事情。不幸的是,我需要几个特定于系统的功能(例如隐藏文件:Python 跨平台隐藏文件)。为可读性和可维护性编写代码的最佳方法是什么?

目前,代码使用许多if语句在不同平台上表现不同。我考虑过的另一种方法是将代码拆分为两个独立的函数,一个用于 Windows,一个用于 Linux,但这意味着在两个地方更新代码的主要部分。

请注意,代码的主要部分比这要长得多,也更复杂。

组合方法(最大的可维护性但有很多if语句):

import os

def sort_out_files():
    if is_linux:
        do_linux_preparations()
    else:
        do_windows_preparations()

    # Main part of the code:
    for file in os.listdir(folder):
        if is_correct_file(file):
            if is_linux:
                do_main_actions_for_linux()
            else:
                do_main_actions_for_windows()

    if is_linux:
        do_linux_tidying_up()
    else:
        do_windows_tidying_up()

Run Code Online (Sandbox Code Playgroud)

单独的方法(需要更多的维护,但需要的if语句更少):

import os

def sort_out_files_linux():
    do_linux_preparations()

    # Main part of the code:
    for file in os.listdir(folder):
        if is_correct_file(file):
            do_main_actions_for_linux()

    do_linux_tidying_up()


def sort_out_files_windows():
    do_windows_preparations()

    # Main part of the code:
    for file in os.listdir(folder):
        if is_correct_file(file):
            do_main_actions_for_windows()

    do_windows_tidying_up()

def sort_out_files():
    if is_linux:
        sort_out_files_linux():
    else:
        sort_out_files_windows()

Run Code Online (Sandbox Code Playgroud)

do_preparations()do_tidying_up()功能包括文件复制,提取等。

is_correct_file() 检查文件是否具有正确的名称和正确的时间戳。

do_main_actions() 涉及分析、移动和隐藏文件。

上面的示例都有效,但似乎不是实现长期代码可维护性的最 Pythonic 或最佳方法。

Meg*_*Ing 5

我会将仅适用于一个操作系统的所有内容放在一个文件中,但名称相同。然后你可以在你的主文件的开头添加这样的东西:

if is_linux:
    import linux_tools as tools
else:
    import windows_tools as tools
Run Code Online (Sandbox Code Playgroud)

如果这两个文件具有相同的接口(例如顶级方法),则它们可以互换使用。

在您的示例中,linux_toolswindows_tools都包含各自的 实现sort_out_files,但都命名为sort_out_files,因此您可以将其与tools.sort_out_files.

请记住在这些模块中保留尽可能多的通用代码。


小智 5

为了使您的代码更易于维护,我建议研究适配器设计模式

例如:您可以创建一个适配器类,而不是每次需要运行特定于操作系统的函数时调用 if 语句。在运行时,您将使用适当的特定于操作系统的实现来创建适配器,并在需要时引用它。

适配器设计的示例:

# Adapter interface
class Adapter:
    def SomeAction():
        raise NotImplementedError

    def SomeOtherAction():
        raise NotImplementedError

# Windows implementation
class WindowsAdapter(Adapter):
    def SomeAction():
        print("Windows action!")

    def SomeOtherAction():
        print("Windows other action!")

# Linux implementation
class LinuxAdapter(Adapter):
    def SomeAction():
        print("Linux action!")

    def SomeOtherAction():
        print("Linux other action!")
Run Code Online (Sandbox Code Playgroud)