pythonwindowsmapped-drivesubst

How to do replicate Window's subst command in Python?


I am trying to map a virtual drive on my windows setup one of the tools I am using does not like the spaces in the filenames.

On the command line, I would do the following

subst l: "c:\Program Files\Complier\version 6.0\bin"

I tried to replicate the functionality in Python without any success. I started using os.execl() to execute the subst command directly, but that reported an invalid parameter error.

Some of the other solutions on SO suggest using the Win32API directly.

By the way, I am using Python 2.7.3 on Windows.


Solution

  • You can call the Windows API directly. Note that you need to pass unicode strings here, or you could set argtypes on the function to get type-safe behaviour.

    from ctypes import windll, c_int, c_wchar_p
    DefineDosDevice = windll.kernel32.DefineDosDeviceW
    DefineDosDevice.argtypes = [ c_int, c_wchar_p, c_wchar_p ]
    
    # Create a subst. Check the return for non-zero to mean success
    if DefineDosDevice(0, "T:", "C:\\Temp") == 0:
        raise RuntimeError("Subst failed")
    
    # Delete the subst.
    if DefineDosDevice(2, "T:", "C:\\Temp") == 0:
        raise RuntimeError("Couldn't remove subst")