Skip to main content
 首页 » 编程设计

python之在 supervisord 下运行时子进程失败

2025年05月04日12mq0036

我有一个发送邮件的 supervisor(e)d python 脚本。当我 ssh 并且脚本从 shell 运行时一切正常。输出是一样的,没有失败,当然,evalue 是 0

evalue = -1 
try: 
   f = tempfile.TemporaryFile() 
   f.write(body.encode('utf-8')) 
   f.seek(0) 
   log.debug("'%s'" % "' '".join(call)) 
   for s in call: 
       log.debug(type(s)) 
   evalue = subprocess.check_call(call, stdin=f) 
except Exception as e: 
    log.exception(e) 
finally: 
    f and f.close() 
    f = None 
log.debug("evalue %s" % evalue) 

我看到了输出:

mailer_v1   : DEBUG    'mailx' '-s' 'test ñññ ' '-a' '/tmp/test_ñññ_0,00_E.pdf' '-r' 'test <code@nebulo.se>' 'test@nebulo.se' 
: DEBUG    <type 'str'> 
mailer_v1   : DEBUG    <type 'str'> 
mailer_v1   : DEBUG    <type 'unicode'> 
mailer_v1   : DEBUG    <type 'str'> 
mailer_v1   : DEBUG    <type 'unicode'> 
mailer_v1   : DEBUG    <type 'str'> 
mailer_v1   : DEBUG    <type 'unicode'> 
mailer_v1   : DEBUG    <type 'unicode'> 
mailer_v1   : ERROR    execv() arg 2 must contain only strings 
Traceback (most recent call last): 
 File "/data/workers/mailer_v1", line 90, in <module> 
   evalue = subprocess.check_call(call, stdin=f) 
 File "/usr/lib/python2.7/subprocess.py", line 506, in check_call 
   retcode = call(*popenargs, **kwargs) 
 File "/usr/lib/python2.7/subprocess.py", line 493, in call 
return Popen(*popenargs, **kwargs).wait() 
 File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ 
   errread, errwrite) 
 File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child 
   raise child_exception 
TypeError: execv() arg 2 must contain only strings 
mailer_v1   : DEBUG    evalue -1 

shell 中的语言环境是 es_ES.UTF-8,在我的 supervisord conf 中有

environment=LC_ALL=es_ES.UTF-8 

谢谢。

请您参考如下方法:

我可以通过在 C 语言环境中运行脚本来重现您的问题:

$ LANG=C python run-subprocess.py 
# -> TypeError: execv() arg 2 must contain only strings 

在这种情况下,所有编码都是 ascii:

import locale 
import sys 
 
print(sys.getfilesystemencoding()) # <-- this is used for args 
print(sys.stdout.encoding) 
print(locale.getpreferredencoding(False)) 
print(locale.getpreferredencoding(True)) 

如果您强制使用 utf-8 编码,那么它会起作用:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
from subprocess import check_call 
 
cmd = [b'-s', u'test ñññ ', b'-a', u'/tmp/test_ñññ_0,00_E.pdf', b'-r', u'test'] 
encoding = 'utf-8' # force utf-8 no matter what 
                   # `sys.getfilesystemencoding()` or 
                   # `locale.getpreferredencoding(True)` say 
check_call(['echo'] + [s.encode(encoding) if isinstance(s, unicode) else s 
                       for s in cmd])