TypeError:execv()arg 2必须仅包含字符串(子进程和Unicode)



我有这个python2.7脚本,如果lang!='c':

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
import os
import subprocess
import sys
print('LANG: {}'.format(os.environ['LANG']))
print('sys.getdefaultencoding(): {}'.format(sys.getdefaultencoding()))
print('sys.getfilesystemencoding(): {}'.format(sys.getfilesystemencoding()))
subprocess.check_call(['echo', 'Umlauts üöä'])

致电Linux Shell:

user@host:~$ python src/execv-arg-2-must-contain-only-strings.py 
LANG: de_DE.UTF-8
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): UTF-8
Umlauts üöä

但这失败了:

user@host:~$ LANG=C python src/execv-arg-2-must-contain-only-strings.py 
LANG: C
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): ANSI_X3.4-1968
Traceback (most recent call last):
  File "src/execv-arg-2-must-contain-only-strings.py", line 12, in <module>
    subprocess.check_call(['echo', 'Umlauts üöä'])
  File "/usr/lib/python2.7/subprocess.py", line 536, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 523, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

我该怎么做才能使此脚本在python2.7上使用lang = c?

使用 lang = c.utf-8 而不是 lang = c

user@host> LANG=C.UTF-8 python t.py
LANG: C.UTF-8
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): UTF-8
Umlauts üöä

: - )

我没有将其发布为答案,因为我没有检查其正确性ATM的手段。但是原则上,如果要以子程序/壳参数的方式发送数据,则必须匹配上述数据的编码(然后将其解码为"接收子程序")或Python不知道如何打包参数。/p>

因此,如果您正在使用utf-8字面的(如编码标题中定义),并且要将其发送到子过程中,则应首先将其解码为 native unicode对象,然后将其编码为系统对当前环境的编码,例如:

literal_argument = "Umlauts üöä"  # string literal
unicode_argument = literal_argument.decode("utf-8")  # unicode
encoded_argument = unicode_argument.encode(sys.getdefaultencoding())  # sys encoded
subprocess.check_call(['echo', encoded_argument])

虽然更安全,但它仍然可以破坏非标准的壳。在可能的情况下,请使用子过程的stdin管道传递不适合当前外壳作为参数的数据 - 那么,只要两个过程都同意使用哪些编码要使用的代码页面,您就不必担心不同的代码页。

相关内容

最新更新