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:
And i need to get output like this:
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.
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.
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:
And i need to get output like this:
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.
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.