在 OSX 上使用 python 将文件复制到网络路径或驱动器
I have a similar question like the one asked here but I need it to work on OSX.
How to copy files to network path or drive using Python
So i want to save a file on a SMB network share. Can this be done?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是可以做到的。首先,通过从 Python 调用如下命令,将 SMB 网络共享挂载到本地文件系统:(
您可以使用
subprocess
模块来完成此操作)。share
是 SMB 网络共享将安装到的目录的名称,我猜它必须是用户可写的。之后,您可以使用 shutdown.copyfile 复制文件。最后,您必须卸载 SMB 网络共享:也许最好在 Python 中创建一个上下文管理器来负责安装和卸载:
上面的代码片段未经测试,但它通常应该可以工作(除了语法之外)我没有注意到的错误)。另请注意,
mounted
与我在其他答案中发布的network_share_auth
上下文管理器非常相似,因此您不妨通过检查您使用的平台来将两者结合起来platform
模块,然后调用相应的命令。Yes, it can be done. First, mount your SMB network share to the local filesystem by calling a command like this from Python:
(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 usingshutil.copyfile
. Finally, you have to un-mount the SMB network share:Probably it's the best to create a context manager in Python that takes care of mounting and unmounting:
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 thenetwork_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 theplatform
module and then calling the appropriate commands.