Ci stiamo preparando per passare a Python 3.4 e aggiunto unicode_literals. Il nostro codice si basa ampiamente sulle tubazioni da/verso utility esterne che utilizzano un modulo subprocess. Il seguente frammento di codice funziona bene su Python 2.7 per tubi stringhe UTF-8 a un sotto-processo:Come risolvere una codifica che migra il sottoprocesso Python in unicode_literals?
kw = {}
kw[u'stdin'] = subprocess.PIPE
kw[u'stdout'] = subprocess.PIPE
kw[u'stderr'] = subprocess.PIPE
kw[u'executable'] = u'/path/to/binary/utility'
args = [u'', u'-l', u'nl']
line = u'¡Basta Ya!'
popen = subprocess.Popen(args,**kw)
popen.stdin.write('%s\n' % line.encode(u'utf-8'))
...blah blah...
le seguenti modifiche gettare questo errore:
from __future__ import unicode_literals
kw = {}
kw[u'stdin'] = subprocess.PIPE
kw[u'stdout'] = subprocess.PIPE
kw[u'stderr'] = subprocess.PIPE
kw[u'executable'] = u'/path/to/binary/utility'
args = [u'', u'-l', u'nl']
line = u'¡Basta Ya!'
popen = subprocess.Popen(args,**kw)
popen.stdin.write('%s\n' % line.encode(u'utf-8'))
Traceback (most recent call last):
File "test.py", line 138, in <module>
exitcode = main()
File "test.py", line 57, in main
popen.stdin.write('%s\n' % line.encode('utf-8'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
Qualsiasi suggerimento per passare UTF-8 a la pipa?
grazie per questo, ho avuto la stessa identica situazione e problema e questo thread è stato di grande aiuto. Ho anche scoperto che in alcuni casi semplici, 'sh.py' (disponibile qui: https://github.com/amoffat/sh) è stato un sostituto drop-in facile, portatile e compatibile per alcuni dei sottoprocessi. follia. – user5359531