Waveter
Waveter

Reputation: 980

Capture all output and error, warning of a command in windows by python

In bash shell of Linux, I can read a command (from file), then execute the command and write all the output, error, and return code to a file. Can I do that by using python in windows.

Upvotes: 1

Views: 1933

Answers (1)

Corey Goldberg
Corey Goldberg

Reputation: 60614

Of course you can. There are many ways to do this.

Assuming you had a text file named commands that contained a command on each line. You could do something like this:

  • open the input file
  • read the next command name from the file
  • execute the command using subprocess
  • redirect stderr to stdout
  • capture the combined output
  • if the command succeeded set return code to 0, otherwise capture the return code from the exception that is thrown.
  • write the return code and output to file

You will want to use: https://docs.python.org/2/library/subprocess.html or https://docs.python.org/3/library/subprocess.html

for example:

import shlex
import subprocess

with open('commands.txt') as fin:
    for command in fin:
        try:
            proc = subprocess.Popen(
                shlex.split(command),
                stderr=subprocess.STDOUT,
                stdout=subprocess.PIPE
            )
            returncode = 0
            output = proc.communicate()[0]
        except subprocess.CalledProcessError as e:
            returncode = e.returncode
            output = e.output
        with open('output.txt', 'w') as fout:
            fout.write('{}, {}'.format(returncode, output))

Upvotes: 1

Related Questions