How do I mount a filesystem using Python?

前端 未结 10 1933
鱼传尺愫
鱼传尺愫 2020-12-16 09:41

I\'m sure this is a easy question, my Google-fu is obviously failing me.

How do I mount a filesystem using Python, the equivalent of running the shell command

相关标签:
10条回答
  • 2020-12-16 10:08

    As others have pointed out, there is no built-in mount function. However, it is easy to create one using ctypes, and this is a bit lighter weight and more reliable than using a shell command.

    Here's an example:

    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.encode(), target.encode(), fs.encode(), 0, options.encode())
      if ret < 0:
        errno = ctypes.get_errno()
        raise OSError(errno, f"Error mounting {source} ({fs}) on {target} with options '{options}': {os.strerror(errno)}")
    
    mount('/dev/sdb1', '/mnt', 'ext4', 'rw')
    
    0 讨论(0)
  • 2020-12-16 10:09

    As others have stated, a direct access to the syscall will not help you, unless you're running as root (which is generally bad, for many reasons). Thus, it is best to call out to the "mount" program, and hope that /etc/fstab has enabled mounts for users.

    The best way to invoke mount is with the following:

    subprocess.check_call(["mount", what])
    

    where what is either the device path, or the mountpoint path. If any problems arise, then an exception will be raised.

    (check_call is an easier interface than Popen and its low-level brethren)

    0 讨论(0)
  • 2020-12-16 10:12

    Another option would be to use the fairly new sh module. According to its documentation it provides fluent integration with Shell commands from within Python.

    I am trying it out now and it looks very promising.

    from sh import mount
    
    mount("/dev/", "/mnt/test", "-t ext4")
    

    Also take a look at baking, which allows you to quickly abstract away commands in new functions.

    0 讨论(0)
  • 2020-12-16 10:13

    Import cdll from ctypes. Then load your os libc, then use libc.mount()

    Read libc's docs for mount parameters

    0 讨论(0)
提交回复
热议问题