将文件复制到网络路径或使用python在OSX上的驱动器
-
29-09-2019 - |
题
解决方案
是的,可以做到。首先,通过从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
模块,然后调用适当的命令。
不隶属于 StackOverflow