user2102508
user2102508

Reputation: 1017

Python 2/3 subprocess.Popen and non ascii characters

I'm trying to execute commands that are passed as strings via subprocess.Popen call, I want to know how to do it in the most platform and python 3/2 agnostic way. Here is an example:

# content of test.py
import subprocess

with open('test.cmd', 'rb') as f:
    cmd = f.read().decode('UTF-8')

print(cmd)

pro = subprocess.Popen('bash',
    stderr=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE)

out, err = pro.communicate(cmd)

pro.wait()
print(out)
print(err)

I'm emulating the passing of string with non-ascii characters by reading it from file, here is the content of test.cmd file:

echo АБВГ

The string reads well, and the output of print(cmd) statement is correct. How ever when I try to pass cmd to communicate function it fails. In python 2 it says that 'ascii' codec can't encode characters, so it seems it tries to convert it to unicode from str and it thinks that the str has only latin1 characters. How should I get the str object encoded in the right way? In python 3 the communicate function expects bytes as input, but what encoding should be used?

Upvotes: 2

Views: 4100

Answers (1)

Greg Eremeev
Greg Eremeev

Reputation: 1840

In python 2 it says that 'ascii' codec can't encode characters, so it seems it tries to convert it to unicode

It tries to encode unicode to str. Try to encode it explicitly pro.communicate(cmd.encode('utf-8'))

Upvotes: 2

Related Questions