Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mount a filesystem using Python?

Tags:

python

unix

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 mount ...?

Obviously I can use os.system to run the shell command, but surely there is a nice tidy, Python interface to the mount system call.

I can't find it. I thought it would just be a nice, easy os.mount().

like image 383
jjh Avatar asked Nov 03 '09 13:11

jjh


People also ask

How do I mount a file in Python?

Using the syscall requires root privileges. Running Python programs as root is (IMO) never to be encouraged. By using the setuid /bin/mount program, your Python program can run with non-root privs. Also note that the mount program is incredibly lightweight ... it isn't like we're spawning a JVM subprocess.

How can a file system be mounted?

You can mount NFS file system resources by using a client-side service called automounting (or AutoFS), which enables a system to automatically mount and unmount NFS resources whenever you access them. The resource remains mounted as long as you remain in the directory and are using a file.

Which command is used to mount file systems?

mount command is used to mount the filesystem found on a device to big tree structure(Linux filesystem) rooted at '/'. Conversely, another command umount can be used to detach these devices from the Tree. These commands tells the Kernel to attach the filesystem found at device to the dir.


1 Answers

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') 
like image 82
Paul Donohue Avatar answered Oct 08 '22 05:10

Paul Donohue