带有多个引号的参数的 Python 子进程调用

问题描述:

我在 bash 中使用以下命令来执行 Python 脚本.

I use the following command in bash to execute a Python script.

python myfile.py -c "'USA'" -g "'CA'" -0 "'2011-10-13'" -1 "'2011-10-27'"

我正在编写一个 Python 脚本来解决这个问题.我目前不得不使用 os.system (我知道,它很糟糕),因为我不知道如何让引号与 subprocess.Popen 一起使用.传入的字符串变量中必须保留内部单引号.

I'm writing a Python script to wrap around this one. I'm currently having to use os.system (I know, it's crappy) since I can't figure out how to get the quotes to work with subprocess.Popen. The inner single quotes must be maintained in the string variables that are passed in.

有人可以帮我确定如何格式化传递给 subprocess.Popen 的第一个变量.

Can someone please help me determine how to format the first variable passed to subprocess.Popen.

您不需要对值进行转义.对进程来说,一切都以字符串的形式传递.

You don't need to escape the values. To the process everything is passed as a string.

您可以使用 shlex 模块找出传递变量的最佳方式:

You can use the shlex module to figure out what is the best way to pass variables:

import shlex
shlex.split('python myfile.py -c "USA" -g "CA" -0 "2011-10-13" -1 "2011-10-27"') 
['python',
 'myfile.py',
 '-c',
 'USA',
 '-g',
 'CA',
 '-0',
 '2011-10-13',
 '-1',
 '2011-10-27']