1

下午好,

我使用这种方法的一个版本来映射十几个驱动器号:

# 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)

只要我没有包含程序正在使用的文件的文件夹,上面的代码就可以很好地工作。

如果我仅在 cmd 窗口中运行相同的命令,并且当我尝试断开驱动器的连接时文件正在使用中,它会返回您确定吗?是/否

如何通过 Py 脚本将此问题传回给用户(或者如果没有其他问题,请强制断开连接以便代码可以继续运行?

4

1 回答 1

0

要强制断开连接尝试/yes这样

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

为了将问题“重定向”给用户,您有(至少)两种可能的方法:

  • 读写子进程的标准输入/输出流
  • 使用退出代码并在必要时再次启动子进程

第一种方法非常脆弱,因为您必须阅读标准输出并解释它特定于您当前的语言环境以及稍后回答也特定于您当前语言环境的问题(例如,确认将使用 'Y' in英语,但德语中带有“J”等)

第二种方法更稳定,因为它或多或少地依赖于静态返回码。我做了一个快速测试,如果取消问题,返回码是 2;如果成功当然只有 0。因此,使用以下代码,您应该能够处理问题并根据用户输入采取行动:

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")
于 2016-07-25T15:06:59.700 回答