如何从 python 中的参数列表格式化 shell 命令行
我有一个参数列表,例如 ["hello", "bobbity bob", "bye"]
。我将如何格式化它们以便将它们正确地传递到 shell?
错误:
>>> " ".join(args)
hello bobbity bob bye
正确:
>>> magic(args)
hello "bobbity bob" bye
I have a list of arguments, e.g. ["hello", "bobbity bob", "bye"]
. How would I format these so they would be passed appropriately to a shell?
Wrong:
>>> " ".join(args)
hello bobbity bob bye
Correct:
>>> magic(args)
hello "bobbity bob" bye
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用未记录但长期稳定的(至少 自 2004 年 10 月起)
subprocess.list2cmdline
:You could use the undocumented but long-stable (at least since Oct 2004)
subprocess.list2cmdline
:解决问题的更简单方法是在文本至少有两个单词时添加“...”。
所以要做到这一点:
The easier way to solve your problem is to add \"...\" whenever your text has at least two words.
So to do that :
如果您实际上将值发送到 shell 脚本,
subprocess.popen
会为您处理此问题:http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen
否则,我相信你会认真对待字符串操纵。
shlex.split
的作用与您想要的相反,但似乎没有相反的情况。If you're actually sending the values to a shell script,
subprocess.popen
handles this for you:http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen
Otherwise, I believe you're down to string manipulation.
shlex.split
does the opposite of what you want, but there doesn't seem to be a reverse.老式方法的问题在于:
即使引用单个词的参数也没关系。
What's wrong with the old-school approach:
It doesn't matter if single-word arguments are quoted as well.