Executing DevCon CMD command from python

2019-04-14 07:21发布

问题:

I want to restart driver with DevCon from python script. It works from command line with this command:

devcon restart \"sd0007322081041363_kcanv\"

I tried this:

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

with result:

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

I read that os.system is obsolete and i need to use subprocess.check_output so i try this:

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

with result:

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

and this:

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

with result:

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

and this:

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

result:

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

and this:

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

with result:

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 is under Windows/System32 and it is set in system path.

I know that this can be duplicate question but I have tried many solution on stackoverflow but i van't resolve this issue.

回答1:

Finally, I came up with a solution. I tried many things but this is what works for me:

  1. copy devcon.exe from C:\Windows\System32 and put it to C:\Windows\SysWOW64.

  2. my code:

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