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


good afternoon,

i used version of method map dozen drive letters:

# drive letter: m # shared drive path: \\shared\folder # username: user123 # password: password import subprocess  # disconnect on m subprocess.call(r'net use * /del', shell=true)  # connect shared drive, use drive letter m subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=true) 

the above code works great long not have folder file in use program.

if run same command in cmd window , file in use when try disconnect drive returns are sure? y/n.

how can pass question user via py script (or if nothing else, force disconnect code can continue run?

to force disconnecting try /yes so

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

in order 'redirect' question user have (at least) 2 possible approaches:

  • read , write standard input / output stream of sub process
  • work exit codes , start sub process second time if necessary

the first approach fragile have read standard output , interpret specific current locale answering later question specific current locale (e.g. confirming done 'y' in english 'j' in german etc.)

the second approach more stable relies on more or less static return codes. did quick test , in case of cancelling question return code 2; in case of success of course 0. following code should able handle question , act on user input:

import subprocess  exitcode = subprocess.call(r'net use * /del /no', shell=true) if exitcode == 2:     choice = input("probably 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") 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -