如何从python中的参数列表格式化shell命令行

2024-09-25 00:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个参数列表,例如["hello", "bobbity bob", "bye"]。我该如何格式化这些文件,以便将它们适当地传递给shell?在

错误

>>> " ".join(args)
hello bobbity bob bye

正确

^{pr2}$

Tags: 文件hello列表参数错误argsshellbob
3条回答

您可以使用未记录但长稳定(至少since Oct 2004subprocess.list2cmdline

In [26]: import subprocess
In [34]: args=["hello", "bobbity bob", "bye"]

In [36]: subprocess.list2cmdline(args)
Out[36]: 'hello "bobbity bob" bye'

解决问题的更简单的方法是在文本中至少有两个单词时添加“…\”。
为此:

# Update the list
for str in args:
  if len(str.split(" ")) > 2:
    # Update the element within the list by
    # Adding at the beginning and at the end \"

    ...

# Print args
" ".join(args)

如果实际要将值发送到shell脚本,subprocess.popen将为您处理此问题:

http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen

否则,我相信你是在操纵琴弦。shlex.split所做的与您想要的相反,但似乎没有相反的结果。在

相关问题 更多 >