0

I am writing a script which is executing CMD commands on Windows. I use it to parse commands to diferent application. Those commands return some values or errors. How do I force Python/CMD to store whatever command returns (no matter if it's returned value or error) in a variable and force it NOT to print it to console. I tried subprocess and os.system() and all of those I tried allows to store value but when command returns an error, it still is being printed to the console and not stored in a variable.

2 Answers2

0

That is a property of the shell / of cmd and how you call the process. By default there's one input stream (stdin) and two output streams (stdout and stderr) - the latter being the default stream for all errors.

You can direct either or both to one another or to stdin or a file by calling the script appropriately. See https://support.microsoft.com/en-us/help/110930/redirecting-error-messages-from-command-prompt-stderr-stdout

For example

myscript 1> output.msg 2>&1

will direct everything into output.msg, including errors. Now combine that output redirection with writing to a variable; that is explained in this answer.

planetmaker
  • 5,884
  • 3
  • 28
  • 37
0

When executing a command in a shell there is 2 different outputs handlers, stdout and stderr. Usually stdout is used to print normal output and stderr to print errors and warnings.

You can use subprocess.Popen.communicate() to read both stderr and stdout.

import subprocess

p = subprocess.Popen(
    "dir", 
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True
)
(stdout, stderr) = p.communicate()

print(stdout.decode('utf-8'))  # Standard output
print(stderr.decode('utf-8'))  # Standard error
wiredrat
  • 76
  • 1
  • 3
  • This solution works but when I used os.system() Python used to execute the command and go on with next lines. But with subprocess.Popen() Python waits with another line, until the application (that I started via CMD) is closed. How to force it to "go on"? – staszkon Dec 04 '19 at 13:04
  • I don't understand what you mean with "waits with another line". Does the command expect an input? If so, you can do `p.communicate(input="whatever you want to send")` to send data to the command standard input. – wiredrat Dec 04 '19 at 13:10
  • from the code you wrote, Python executes: 'import subprocess cmd = subprocess.Popen("udt.exe", stdout=subprocess.PIPE, stderr=subprocess.PIPE) #the app it runs is a window application' and then pauses. nothing happens. if I manually close the udt.exe application, Python code resumes and executes whatever is next – staszkon Dec 04 '19 at 15:19