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

标签 python subprocess

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

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

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

谁能帮我确定如何格式化传递给 subprocess.Popen 的第一个变量。

最佳答案

您不需要对这些值进行转义。一切都作为字符串传递给流程。

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

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']

关于带有多个引号的参数的 Python 子进程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8581140/

相关文章:

python - 如何从字典中获取随机选择的值

python - 在 python 中执行无操作的标准方法是什么?

python - 如何以简单的方式使 matplotlib 标记对色盲友好?

python - 使用python读取php文件的输出

python - 为什么Python拒绝在新的子进程中执行这段代码?

python - 列表 Python 中两个字典值的最大平均值

python - 如何将错误消息从 shell 脚本传递到 Python 脚本?

Python 3 子进程管道 block

python - 为什么 shell=True 将命令连接在一起时可以工作?

python - 执行 GUI onclick 命令时,将变量值从一个模块返回到另一个模块时出现问题