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

发布于 2024-12-01 09:58:20 字数 302 浏览 1 评论 0原文

我有一个参数列表,例如 ["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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

献世佛 2024-12-08 09:58:20

您可以使用未记录但长期稳定的(至少 自 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'

You could use the undocumented but long-stable (at least since Oct 2004) subprocess.list2cmdline:

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

In [36]: subprocess.list2cmdline(args)
Out[36]: 'hello "bobbity bob" bye'
微凉 2024-12-08 09:58:20

解决问题的更简单方法是在文本至少有两个单词时添加“...”。
所以要做到这一点:

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

The easier way to solve your problem is to add \"...\" whenever your text has at least two words.
So to do that :

# 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)
执笔绘流年 2024-12-08 09:58:20

如果您实际上将值发送到 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.

<逆流佳人身旁 2024-12-08 09:58:20

老式方法的问题在于:

>>> args = ["hello", "bobbity bob", "bye"]
>>> s = ""
>>> for x in args:
...     s += "'" + x + "' "
...
>>> s = s[:-1]
>>> print s
'hello' 'bobbity bob' 'bye'

即使引用单个词的参数也没关系。

What's wrong with the old-school approach:

>>> args = ["hello", "bobbity bob", "bye"]
>>> s = ""
>>> for x in args:
...     s += "'" + x + "' "
...
>>> s = s[:-1]
>>> print s
'hello' 'bobbity bob' 'bye'

It doesn't matter if single-word arguments are quoted as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文