我确信这是一个简单的问题,我的Google-fu显然让我失望了.
如何使用Python挂载文件系统,相当于运行shell命令mount ...?
显然我可以os.system用来运行shell命令,但是肯定有一个很好的整洁的Python接口来挂载系统调用.
我找不到它.我认为这将是一个很好的,简单的os.mount().
Pau*_*hue 39
正如其他人所指出的那样,没有内置的挂载功能.但是,使用ctypes很容易创建一个,这比使用shell命令更轻,更可靠:
import ctypes
import ctypes.util
import os
libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p)
def mount(source, target, fs, options=''):
ret = libc.mount(source, target, fs, 0, options)
if ret < 0:
errno = ctypes.get_errno()
raise OSError(errno, "Error mounting {} ({}) on {} with options '{}': {}".
format(source, fs, target, options, os.strerror(errno)))
mount('/dev/sdb1', '/mnt', 'ext4', 'rw')
Run Code Online (Sandbox Code Playgroud)
sam*_*mvv 13
另一种选择是使用相当新的sh模块.根据其文档,它提供了与Python内部的Shell命令的流畅集成.
我现在正在尝试它,它看起来很有希望.
from sh import mount
mount("/dev/", "/mnt/test", "-t ext4")
Run Code Online (Sandbox Code Playgroud)
另外,请看一下烘焙,它允许您快速抽象出新功能中的命令.
yeg*_*ich 10
您可以libmount从util-linux项目使用Python绑定:
import pylibmount as mnt
cxt = mnt.Context()
cxt.source = '/dev/sda1'
cxt.target = '/mnt/'
cxt.mount()
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅此示例.
正如其他人所说,直接访问系统调用不会对您有帮助,除非您以 root 身份运行(由于多种原因,这通常是不好的)。因此,最好调用“挂载”程序,并希望已/etc/fstab为用户启用挂载。
调用挂载的最佳方法如下:
subprocess.check_call(["mount", what])
Run Code Online (Sandbox Code Playgroud)
其中what是设备路径或安装点路径。如果出现任何问题,则会引发异常。
(是一个比它的低级兄弟check_call更简单的界面)Popen
Fer*_*yer -16
当然,这是一个漂亮整洁的 mount 系统调用的 python 接口。
我找不到它(我认为这只是一个很好、简单的 os.mount())。
当然,没有。这个函数在 Windows 上会做什么?
请改用 shell 命令。