在OSX上使用python将文件复制到网络路径或驱动器 [英] Copy files to network path or drive using python on OSX
问题描述
我有一个类似的问题,例如这里的问题,但我需要在OSX上使用它.
I have a similar question like the one asked here but I need it to work on OSX.
所以我想将文件保存在SMB网络共享上.能做到吗?
So i want to save a file on a SMB network share. Can this be done?
谢谢!
推荐答案
是的,可以做到.首先,通过从Python调用以下命令,将SMB网络共享安装到本地文件系统:
Yes, it can be done. First, mount your SMB network share to the local filesystem by calling a command like this from Python:
mount -t smbfs //user@server/sharename share
(您可以使用subprocess
模块执行此操作). share
是将SMB网络共享安装到的目录的名称,我想它必须是用户可写的.之后,您可以使用shutil.copyfile
复制文件.最后,您必须卸载SMB网络共享:
(You can do it using the subprocess
module). share
is the name of the directory where the SMB network share will be mounted to, and I guess it has to be writable by the user. After that, you can copy the file using shutil.copyfile
. Finally, you have to un-mount the SMB network share:
umount share
最好用Python创建一个上下文管理器,该上下文管理器负责挂载和卸载:
Probably it's the best to create a context manager in Python that takes care of mounting and unmounting:
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
模块检查所使用的平台,然后调用适当的命令来将两者结合
The above code snippet is not tested, but it should work in general (apart from syntax errors that I did not notice). Also note that mounted
is very similar to the network_share_auth
context manager I posted in my other answer, so you might as well combine the two by checking what platform you are on using the platform
module and then calling the appropriate commands.
这篇关于在OSX上使用python将文件复制到网络路径或驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!