从 Windows、Mac 和 Linux 访问网络共享

问题描述 投票:0回答:1

我需要使用 Python 从网络共享读取文件。 Python 程序需要在 macOS、Windows(我们在开发团队中使用的系统)和 Linux(服务器正在运行的系统)上运行。

在 macOS 中,我可以像这样从安装的网络共享中读取:

file_path = '//Volumes/data/path/to/files'
list_of_files = os.listdir(file_path)

在 Windows 中我可以做

file_path = 'V:\path\to\files'
list_of_files = os.listdir(file_path)

或者另一种选择

file_path = '//our.server.de/share/data/path/to/files'
list_of_files = os.listdir(file_path)

我确信Linux中有类似的东西(我还没有尝试过)。

我想我可以以某种方式确定当前的操作系统并使用 if 语句,但我希望有更好的方法来实现这一点。

我希望能够通过网络而不是本地文件系统以某种方式获取文件(如果这有意义的话)。

非常感谢任何提示!

python python-3.x network-programming
1个回答
0
投票

根据上面@Some程序员的评论,我认为这可能是解决方案:

import os
import platform

def set_path_root():
    if platform.system() == 'Darwin':
        os.system("osascript -e 'mount volume \"smb://our.server.de/share/data\"'") 
        path_root = '//Volumes/data'
    
    elif platform.system() == 'Windows':
        path_root = '//our.server.de/share/data'

    elif platform.system() == 'Linux':
        path_root = '/whatever/works/on/Linux'

  return path_root

path_root = set_path_root()

file_path = f'{path_root}/path/to/files'

list_of_files = os.listdir(file_path)

有关 platform.system() 的值,请参阅这个问题。有关在 macOS 中安装卷的信息,请参阅这个问题

© www.soinside.com 2019 - 2024. All rights reserved.