从 python 执行 DevCon CMD 命令

Executing DevCon CMD command from python

我想从 python 脚本使用 DevCon 重新启动驱动程序。它从命令行使用此命令工作:

devcon restart \"sd0007322081041363_kcanv\"

我试过这个:

os.system("devcon restart \"sd0007322081041363_kcanv\"")

结果:

'devcon' is not recognized as an internal or external command

我读到 os.system 已过时,我需要使用 subprocess.check_output 所以我试试这个:

subprocess.check_output(['devcon', 'restart', '"sd0007322081041363_kcanv"'])

结果:

WindowsError:[Error 2] The system cannot find the file specified

还有这个:

subprocess.check_output('devcon restart "sd0007322081041363_kcanv"', shell=True)

结果:

subprocess.CalledProcessError: Command 'devcon restart "sd0007322081041363_kcanv"' returned non-zero exit status 1

还有这个:

subprocess.Popen("devcon restart \"sd0007322081041363_kcanv\"", shell=True, stdout=subprocess.PIPE).stdout.read()

结果:

'devcon' is not recognized as an internal or external command

还有这个:

try:
    subprocess.check_output('devcon disable "sd0007322081041363_kcanv" /f',shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

结果:

RuntimeError: command 'devcon disable "sd0007322081041363_kcanv" /f' return with errpr (cpde 1): 'devcon' is not recognized as an internal or external command, operable program or batch file

devcon.exe在Windows/System32下,在系统路径中设置。

我知道这可能是重复的问题,但我在 Whosebug 上尝试了很多解决方案,但我无法解决这个问题。

最后,我想出了一个解决办法。我尝试了很多东西,但这对我有用:

  1. 从 C:\Windows\System32 复制 devcon.exe 并放到 C:\Windows\SysWOW64。

  2. 我的代码:

    try:
        subprocess.check_output('C:\Windows\SysWOW64\devcon.exe restart "sd0007322081041363_kcanv" /f',shell=True,stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))