简体   繁体   中英

How do i mount a usb device or a hard drive partition using python

I have been trying to write a program that would mount a device in a specified location, everything will be done by the user inputs.

I have used ctypes . The place where I'm stuck is at this part

 def mount(source, target, fs, options=''):
  ret = ctypes.CDLL('libc.so.6', use_errno=True).mount(source, target, fs, 0, options)
  if ret < 0:
   errno = ctypes.get_errno()
   raise RuntimeError("Error mounting {} ({}) on {} : {}".
    format(source, fs, target, os.strerror(errno)))

I'm receiving an error saying 'Invalid argument' and that is at

mount(a, b, 'ntfs', ' -w')

The following is my whole code:

import os
import ctypes

print "Usb device management"

def mount(source, target, fs, options=''):
ret = ctypes.CDLL('libc.so.6', use_errno=True).mount(source, target, fs, 0, options)
 if ret < 0:
errno = ctypes.get_errno()
raise RuntimeError("Error mounting {} ({}) on {} : {}".
    format(source, fs, target, os.strerror(errno)))

def umount(source):
 retu = ctypes.CDLL('libc.so.6', use_errno = True).umount(source)
  if retu < 0:
    errno1 = ctypes.get_errno1()
    raise RuntimeError("error unmounting {} ".
        format(source))


while True :
print "\n 1. Mount \n 2. Unmount \n 3. Write to file \n 4. Read File \n 5. Copy \n 6. Exit"
choice  = int(raw_input('Enter the choice : '))

if choice == 1:
    a = raw_input('Enter device name ')
    b = raw_input('Enter mount location ')
    mount(a, b, 'ntfs', ' -w')
    print "USB mounted"

elif choice == 2:
    print "Unmounting USB device"
    c=raw_input('Enter USB device location ')
    umount (c)
    print "USB device unmounted"
elif choice == 3:
    string = raw_input('Give input to write to file')
    fd = open("%s/file.txt"%(b), 'w')
    fd.write('string')
    print "file Write successfull"
    fd.close()
elif choice == 4:
    print "Reading file"
    fd = open("%s/file.txt"%(b),'r')
    print "File read successfull "
    fd.close()
elif choice == 5:
    copy_location = raw_input('Enter location to where it has to be copied')
    print "Copying file "
    os.system("cp %s/file.txt %s"%(b, copy_location))
    print "%s  %s"%(b, copy_location)
    print("File copied to location $s "%(copylocation))
if choice == 6:
    print "Exit bye"
    break;

And my system is Ubuntu 15.10.

if you look at man 2 mount , you'll see that the mount flags has to be a number, not a string. This is an obvious error; whether it's all the errors you have, I cannot say.

I would just use the command line mount.

import os
os.system("mount /dev/sd(x) /mountpoint") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM