python subprocess 和 unicode execv() arg 2 必须只包含字符串 [英] python subprocess and unicode execv() arg 2 must contain only strings

查看:21
本文介绍了python subprocess 和 unicode execv() arg 2 必须只包含字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 django 站点,我需要在其中使用子进程调用脚本.当我使用 ascii 字符时,子进程调用有效,但是当我尝试发出 utf-8 编码的参数时,出现错误:

I have a django site where I need to call a script using subprocess. The subprocess call works when I'm using ascii characters but when I try to issue arguments that are utf-8 encoded, I get an error:

execv() arg 2 must contain only strings.

字符串 u'Wiadomo\u015b\u0107' 来自 postgres 数据库.此示例使用波兰语单词.当我使用英文单词运行它时,我没有问题.

The string u'Wiadomo\u015b\u0107' is coming from a postgres db. This example is using polish words. When I run it using english words, I have no issues.

调用如下所示:

subprocess.Popen(['/usr/lib/p3web2/src/post_n_campaigns.py', '-c', u'bm01', '-1', u'Twoja', '-2', u'Wiadomo\u015b\u0107', '-3', u'', '-4', u'', '-5', u'', '-6', u'', '-m', u'pl', '-p', 'yes'])

我不确定在这种情况下如何处理字符串.奇怪的是,当我通过 python 解释器运行它时,这工作正常.

I'm not sure how to handle the strings in this case. The odd thing is that this works fine when i run it through the python interpreter.

推荐答案

您应该按照程序期望的编码方式对 Unicode 字符串进行编码.如果您知道程序需要 UTF-8:

You should encode the Unicode strings in the encoding your program expects. If you know the program expects UTF-8:

u'Wiadomo\u015b\u0107'.encode('utf8')

如果你不知道你需要什么编码,你可以试试你平台的默认编码:

If you don't know what encoding you need, you could try your platform's default encoding:

u'Wiadomo\u015b\u0107'.encode()

这篇关于python subprocess 和 unicode execv() arg 2 必须只包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆