带有多个引号的参数的 Python 子进程调用 [英] Python subprocess call with arguments having multiple quotations

查看:35
本文介绍了带有多个引号的参数的 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']

这篇关于带有多个引号的参数的 Python 子进程调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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