Batch-Befehl mit Python in Textdatei speichern?
Ich will mit Python die Ausgabe eines Batch-Befehls in einer Textdatei speichern. Im Batch-Output sind aber Zeilenumbrüche vorhanden, welche in der Textdatei als \n angezeigt werden. Der ganze Output wird somit in eine Zeile geschrieben und ist beinahe unlesbar. Wie schaffe ich es, \n in der Textdatei auch tatsächlich als Zeilenumbruch anzuzeigen?
Hier der Code:
import subprocess
result = subprocess.run(["ipconfig", "/all"], capture_output=True)
if result.returncode == 0: #0 = exit code for programm_succesfully_executed
try:
if result.stdout is not None and result.stdout.strip(): #if output is not empty
with open("ipconfig_output.txt", "w", encoding="utf-8",) as file: #opening file
file.write(str(result.stdout)) #writing file
print("writing done")
else:
print("ipconfig is empty")
except Exception as e:
print(f"a problem occured.\nERROR: {e}")
else:
print(f"trouble while exeuting:\n{result.stderr}")
1 Antwort
Von gutefrage auf Grund seines Wissens auf einem Fachgebiet ausgezeichneter Nutzer
Programmiersprache
Die Konsole gibt ihren Output normalerweise nicht in utf-8 zurück, sondern in der lokalen Codepage. In Europa dürfte das fast immer Codepage 850 sein. Bei mir hat es geklappt, wenn ich das beim umwandeln angebe.
Also statt:
file.write(str(result.stdout))
machst du das:
file.write(str(result.stdout, endoding='cp850'))