Goal of this question: I am trying to extract the output of the command I run in cmd into a file. I do use a file to run the commands from as I have many items to run.
The file and the data/commands in it look something like this: text file with commands
I want to run every line and extract the results even if the cmd returned a non-zero result.
How can I;
A. Improve on either code below so that I can reduce the runtime and make it faster?
B. does anyone have an idea on a procedure/process/code that I can utilize that would get me my end result faster?
Thank you!
expected results are something similar to this: Results of pinging two hosts. one failed, one passed
The '#' is not necessary.
Now here are a couple of items I have tried: Code 1: it works BUT IS VERY SLOW.
cmds_file = pathlib.Path(r"C:\Users\filepath").joinpath("command text file")
output_file = pathlib.Path(r"C:\Users\filepath").joinpath("results text file")
with open(cmds_file, encoding="utf-8") as commands, open(output_file, "w", encoding="utf-8")
as output:
for command in commands:
command = shlex.split(command)
output.write(f"\n# {shlex.join(command)}\n")
output.flush()
subprocess.run(command, stdout=output, encoding="utf-8")
Code 2: does not extract failed results(I know it wont with the below code as I do not have anything under the 'except' section but I have tried many things. and for some reason won't loop through the items in the file anymore.
command_path = pathlib.Path(r"C:\Users\path to file")
command_file = command_path.joinpath('command file')
commands = command_file.read_text().splitlines()
#print(commands)
try:
for command in commands:
#Args = command.split()
#print(f"/Running: {Args[0]}")
#response = subprocess.call(command)
outputfile = subprocess.check_output(command)
results_path = command_path.joinpath(f"Testingfile_results.txt")
results = open(results_path, "a").write('\n' + outputfile.decode("utf-8"))
results.close()
except:
print(command, 'returned non zero results')
I hope this makes sense, and if any more clarification needed please ask and I will clarify. Thank you for your time.