如何在Python中根据参数列表格式化Shell命令行

7 投票
4 回答
3148 浏览
提问于 2025-04-17 00:20

我有一串参数,比如 ["hello", "bobbity bob", "bye"]。我该怎么处理这些参数,让它们能正确地传递给命令行呢?

错误的做法:

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

正确的做法:

>>> magic(args)
hello "bobbity bob" bye

4 个回答

1

解决你问题的简单方法是,当你的文本中至少有两个单词时,就加上\"...\"。
所以要做到这一点:

# 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)
1

如果你真的要把这些值发送给一个 shell 脚本,subprocess.popen 会帮你处理这些事情:

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

否则,我觉得你就得自己处理字符串了。shlex.split 做的正好是你不想要的事情,但似乎没有一个可以反向操作的工具。

17

你可以使用一个没有正式文档但已经很稳定的功能(至少从2004年10月起就开始使用了)叫做 subprocess.list2cmdline

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

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

撰写回答