Search code examples
pythonsubprocessnet-use

Mapping Window Drives Python: How to handle when the Win cmd Line needs input


Good Afternoon,

I used a version of this method to map a dozen drive letters:

# Drive letter: M
# Shared drive path: \\shared\folder
# Username: user123
# Password: password
import subprocess

# Disconnect anything on M
subprocess.call(r'net use * /del', shell=True)

# Connect to shared drive, use drive letter M
subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True)

The above code works great as long as I do not have a folder with a file in use by a program.

If I run the same command just in a cmd window and a file is in use when I try to disconnect the drive it returns the Are you sure? Y/N.

How can I pass this question back to the user via the Py script (or if nothing else, force the disconnect so that the code can continue to run?


Solution

  • To force disconnecting try it with /yes like so

    subprocess.call(r'net use * /del /yes', shell=True)  
    

    In order to 'redirect' the question to the user you have (at least) 2 possible approaches:

    • Read and write to the standard input / output stream of the sub process
    • Work with exit codes and start the sub process a second time if necessary

    The first approach is very fragile as you have to read the standard output and interpret it which is specific to your current locale as well as answering later the question which is also specific to your current locale (e.g. confirming would be done with 'Y' in English but with 'J' in German etc.)

    The second approach is more stable as it relies on more or less static return codes. I did a quick test and in case of cancelling the question the return code is 2; in case of success of course just 0. So with the following code you should be able to handle the question and act on user input:

    import subprocess
    
    exitcode = subprocess.call(r'net use * /del /no', shell=True)
    if exitcode == 2:
        choice = input("Probably something bad happens ... still continue? (Y/N)")
        if choice == "Y":
            subprocess.call(r'net use * /del /yes', shell=True)
        else:
            print("Cancelled")
    else:
        print("Worked on first try")