Search code examples
pythonshellcmdsymbolspopen

os.popen strange codec issue


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.


Solution

  • I have no idea how to make os.popen use a specific encoding(and I don't think its possible), so here is a solution using subprocess:

    import subprocess
    
    output = subprocess.run("dir", shell=True, encoding="cp866", stdout=subprocess.PIPE).stdout
    print(output)
    

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