subprocess.Popen 和 space 参数中的字符

subprocess.Popen and space character in the arguments

我在 OSX Yosemite 上使用 Python 2.7 将桌面应用程序打包到 Web 应用程序中。

The documentation says the following:

Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names)”

…还有

the use of shell=True is strongly discouraged in cases where the command string is constructed from external input

这就是为什么我用长长的参数列表和 shell=False

调用 subprocess.Popen

无论文档中写了什么,我在传递包含 space 的参数时遇到问题。 在 fork 之后的调试器中,我看到我的参数直接转到 os._execvpe 而没有任何 changes/escaping。 然而,我启动的应用程序仅接收该参数的第一个 space 分隔部分。

有没有办法修复 subprocess.Popen 以使其按记录工作?提前致谢。

P.S。难道是因为我列表中一半的参数是 ASCII 字符串,另一半是 Unicode 字符串?

更新: 这是 Python 代码:

p = subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE )

这里是参数的截断列表:

['/Library/WebServer/Documents/XXX.app/Contents/MacOS/XXX',
'-project', u'/Library/WebServer/Documents/XXX.YYY',
'-user', u'bec4aed7-2ee2-4ec9-0f92-a301ee9d0115',
'-log', u'/Library/WebServer/Documents/Users/bec4aed7-2ee2-4ec9-0f92-a301ee9d0115/renderLog.txt',
'-text', '1', u'one two three four']

应用程序仅接收 u'一二三四' 参数的第一部分。

对我有用的解决方案是将所有命令行参数转换为 Unicode,然后转义它们。

这是我的转义方法,请注意它是如何在空格前加上反斜杠的:

@staticmethod
def _escape_string( val ):
    # Make unicode
    val = unicode( val )
    # Escape stuff
    val = val.replace( u'\', u'\\' )
    val = val.replace( u' ', u'\ ' )
    return val

更改之后,我的子进程开始接收完整的字符串。