使用Python在OSX上将文件复制到网络路径或驱动器
1 个回答
19
是的,这个是可以实现的。首先,你需要通过在Python中运行一个命令,把你的SMB网络共享挂载到本地文件系统上:
mount -t smbfs //user@server/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
模块检查你所处的平台,然后调用相应的命令,把两者结合起来。