Problems executing commands in CMD with Python

Asked

Viewed 2,024 times

2

I am unable to execute (or get the result) commands executed in Windows by Python.
I picked up some code examples I saw on various websites and responses 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)

The only feedback I get 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 have tried running as an administrator. I have tried on another machine. I have tried several different commands, dir is just an example. I have tried changing the parameters of Popen.

Note: The .encode() I put in the argument of communicate() was on my own (also tried with b''). From what I researched, Python recently changed the data entry pattern from several native string functions to bytes, although all the examples I thought of this method were using string.

1 answer

2


Exception: [Winerror 2] The system cannot find the file specified

This exception is cast because the system does not recognize dir as an executable, you must 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. Waits until the command is completed. If the return code has been zero then continue, if contrary to the exception CalledProcessError is launched.

Maybe the method you’re looking for is the subprocess.check_output which executes 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 the subprocess.Popen:

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

print (saida, erros)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.