This stdout doesn’t work in UTF-8 as my Visual Studio Code and my computer (chcp 850
)
Estado de los medios. . . . . . . . . . . : medios desconectados Sufijo DNS espec¡fico para la conexi¢n. . : Descripci¢n . . . . . . . . . . . . . . . : Microsoft Wi-Fi Direct Virtual Adapter Direcci¢n f¡sica. . . . . . . . . . . . . : E0-C2-64-64-FA-92 DHCP habilitado . . . . . . . . . . . . . : s¡ Configuraci¢n autom tica habilitada . . . : s¡
Code:
import subprocess
def ejecutar_comando(comando_Red):
resultado = subprocess.run(comando_Red, shell=True, capture_output=True, text=True)
return resultado.stdout.strip('UTF-8')
comando_Red = [
"ipconfig /all",
"getmac"
]
for comando_Red in comando_Red :
salida = ejecutar_comando(comando_Red)
print (salida)
I was expecting an UTF-8 output with things like í, á, ó, ú….
my cmd and powershell work in chcp 850
and show proper Latin characters.
2
Answers
Thanks everyone, i solved by adding cp850 and changing a little bit the structure. Asuming i just had kind of a mess at printing the output, then my cmd just went crazy.
import subprocess
Execute the command and capture output
result = subprocess.run(['systeminfo'], capture_output=True, text=True, encoding='cp850')
print output
print(result.stdout)
Your understanding of character encoding is clearly incomplete. If the console is configured for code page 850 then that’s what you should tell Python, and expect from the output (and not, for example, UTF-8).
Assuming that the subprocess produces output in this encoding,
The crucial addition is
encoding='cp850'
which tells Python how to decode the output from the subprocess..strip('UTF-8')
would remove any occurrence of U, T, F, -, or 8 on either side of the string, but that’s clearly not required or correct here.Tangentially, I don’t believe
shell=True
is necessary or useful here, so I removed that, too.This still requires your Python to be configured to correctly encode output for the current code page. Please refer to Python, Unicode, and the Windows console for details about that.
More likely, your console is actually cp1252.
If you need help identifying encodings, I humbly offer you https://tripleee.github.io/8bit/
If you have
xa2
and want to check in which encodings that corresponds toó
, see https://tripleee.github.io/8bit/#a2Perhaps see also the Stack Overflow
character-encoding
tag info page