How do I mount a filesystem using Python?

前端 未结 10 1932
鱼传尺愫
鱼传尺愫 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 09:48

    Badly, mounting and unmounting belongs to the things that are highly system dependent and since they are

    • rarely used and
    • can affect system stability

    There is no solution that is portable available. Since that, I agree with Ferdinand Beyer, that it is unlikely, a general Python solution is existing.

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

    You can use Python bindings for libmount from util-linux project:

    import pylibmount as mnt
    
    cxt = mnt.Context()
    cxt.source = '/dev/sda1'
    cxt.target = '/mnt/'
    cxt.mount()
    

    For more information see this example.

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

    Mounting is a pretty rare operation, so it's doubtful that there is any direct python way to do it.

    Either use ctypes to do the operation directly from python, or else (and probably better), use subprocess to call the mount command (don't use os.system() - much better to use subprocess).

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

    Note that calling your libc mount function will require root privileges; Popen(['mount'...) only will if the particular mounting isn't blessed in fstab (it is the mount executable, setuid root, that performs these checks).

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

    I know this is old but I had a similar issue and pexpect solved it. I could mount my Windows shared drive using the mount command but I couldn't pass my password in because it had to be escaped. I grew tired of escaping it and tried to use a credentials file which also caused issues. This seems to work for me.

    password = "$wirleysaysneverquit!!!"
    
    cmd = "sudo mount -t cifs -o username=myusername,domain=CORPORATE,rw,hard,nosetuids,noperm,sec=ntlm //mylong.evenlonger.shareddrivecompany.com/some/folder /mnt/folder -v"
    p = pexpect.spawn( cmd )
    p.expect( ": " )
    print( p.before + p.after + password )
    p.sendline( password )
    p.expect( "\r\n" )
    
    output = p.read()
    arroutput = output.split("\r\n")
    for o in arroutput:
        print( o )
    

    Source: https://gist.github.com/nitrocode/192d5667ce9da67c8eac

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

    surely this 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()).

    Surely, there is none. What would this function do on Windows?

    Use the shell command instead.

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