os.popen strange codec issue

Question:

So im trying to use os.popen to run cmd comands, but the problem is that most of the comands have cyrillic characters in them that seem to have some issues with os.popen. When i use this code

import os

stream = os.popen("dir")
output = stream.read()
print(output)

I get output like this:

enter image description here

And i need to get output like this:

enter image description here

Also i tried to do this with subprocess library but it is much harder to work with subprocess library and i couldnt get encoding done correctly after really long time so i really want to do this with os library if it is possible.

Asked By: Limofeus

||

Answers:

Instead of using os.popen, you can use subprocess.run to execute a command and specify the encoding to use for the input and output. Here’s the best example:

import subprocess
try:
    result = subprocess.run(command, shell=True, encoding='cp866', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = result.stdout
except subprocess.CalledProcessError as e:
    output = str(e)
print(output)

Edit: dir is a shell builtin, so you need shell=True, but you can use a list arg for normal commands.

Answered By: SuperStormer
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.