Reputation: 980
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
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:
subprocess
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