Problems executing commands in CMD with Python

1

I am not able to execute (or get the result) of commands executed in Windows by Python. I got a code sample I saw on various sites and answers in the OS, but none worked well for me.

import subprocess

# Exception: [WinError 2] The system cannot find the file specified
stdout = subprocess.check_call(['dir'])

proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = True, bufsize = 1)    
stdout, stderr = proc.communicate('dir c:\'.encode())
# Retorna sempre a mesma coisa
print(stdout)

Only return I have from the above print is always this:

  

b'Microsoft Windows [Version 10.0.10586] \ r \ n (c) 2015 Microsoft Corporation. All rights reserved. \ R \ n \ r \ nC: \ Users \ Daniel & More? '

I've tried to run as administrator. I've tried another machine. I've tried several different commands, dir is just an example. I already tried changing the parameters of Popen .

Note: The .encode() I put in the communicate() argument was on my own (I've already tried b'' ). As I researched, Python recently changed the input pattern of several native string functions to bytes, although all examples I thought of this method were using string.

    
asked by anonymous 25.08.2016 / 23:09

1 answer

2
  

Exception: [WinError 2] The system can not find the specified file

This exception is thrown because the system does not recognize dir as an executable, you should pass it as an argument to cmd.exe.

import subprocess

try:
    subprocess.check_call(["cmd.exe", "dir"])
except subprocess.CalledProcessError as e:                             
    print ("error code: {}".format(e.returncode))

According to the method documentation subprocess.check_call :

  

Executes the command with arguments. Wait until the command is   completed. If the return code was zero, then continue, if   otherwise the CalledProcessError exception is thrown.

Perhaps the method you're looking for is subprocess.check_output that runs the command and returns the output:

try:
    saida = subprocess.check_output(["cmd.exe", "/C", "dir"]) 
    print (saida)

except subprocess.CalledProcessError as e:                            
    print ("error code: {}".format(e.returncode))

If you prefer to use subprocess.Popen :

pop = subprocess.Popen(["cmd.exe", "/C", "dir"], stdout=subprocess.PIPE)
saida, erros = pop.communicate()

print (saida, erros)
    
25.08.2016 / 23:46