在OSX上使用python将文件复制到网络路径或驱动器

问题描述:

我有一个类似的问题,就像这里提到的问题,但我需要它在OSX上工作。在OSX上使用python将文件复制到网络路径或驱动器

How to copy files to network path or drive using Python

所以我想保存在SMB网络共享的文件。这可以做到吗?

谢谢!

是的,它可以做到。首先,从Python中调用这样的命令mount你的SMB网络共享到本地文件系统:

mount -t smbfs //[email protected]/sharename share 

(您可以使用subprocess模块做到这一点)。 share是SMB网络共享将被加载到的目录的名称,我猜它必须是用户可写的。之后,您可以使用shutil.copyfile复制文件。最后,你要卸载这个SMB网络共享:

umount share 

也许这是最好的在Python中创建一个上下文管理器,需要安装和卸载的护理:

from contextlib import contextmanager 
import os 
import shutil 
import subprocess 

@contextmanager 
def mounted(remote_dir, local_dir): 
    local_dir = os.path.abspath(local_dir) 
    retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir]) 
    if retcode != 0: 
     raise OSError("mount operation failed") 
    try: 
     yield 
    finally: 
     retcode = subprocess.call(["/sbin/umount", local_dir]) 
     if retcode != 0: 
      raise OSError("umount operation failed") 

with mounted(remote_dir, local_dir): 
    shutil.copy(file_to_be_copied, local_dir) 

上面的代码片断没有经过测试,但它应该一般工作(除了语法错误,我没有注意到)。还请注意,mounted与我在其他答案中发布的network_share_auth环境管理器非常相似,因此您可以通过检查使用platform模块的什么平台,然后调用相应的命令来将两者结合起来。

+0

酷!得到它的工作!感谢您的快速(和精心制作的)回复! (想投票,但没有足够的代表: - |) – Gumbah 2010-06-22 10:41:17