什么是shlex.split的反面?

Mat*_*ner 38 python shell split shlex

我怎样才能扭转结果shlex.split呢?也就是说,如果给出一个我希望引用的字符串,我怎样才能获得一个"类似于Unix shell"list的带引号的字符串?

Update0

我找到了一个Python错误,并在此处提出了相应的功能请求.

Éri*_*ujo 26

我们现在(3.3)有一个shlex.quote函数.pipes.quote移动和记录的是其中任何一个(代码使用pipes.quote仍然有效).有关整个讨论,请参见http://bugs.python.org/issue9723.

subprocess.list2cmdline是一个不应该使用的私有函数.然而,它可以移动shlex并正式公开.另见http://bugs.python.org/issue1724822.

  • 也许在答案本身中添加一个实际示例,以说明如何使用`shlex.quote`可能会很好?在https://bugs.python.org/issue22454,他们建议使用`''.join(在split_command中对x使用x(.lex.quote(x)))应该足够。 (2认同)

tok*_*and 19

怎么用pipes.quote

import pipes
strings = ["ls", "/etc/services", "file with spaces"]
" ".join(pipes.quote(s) for s in strings)
# "ls /etc/services 'file with spaces'"
Run Code Online (Sandbox Code Playgroud)

.

  • `pipes.quote`不是Windows安全的.Windows需要双引号 (2认同)

Mat*_*man 10

有一个添加的功能请求shlex.join(),这将完全符合您的要求。不过,截至目前,它似乎没有任何进展,主要是因为它主要只是转发到shlex.quote(). 在错误报告中,提到了建议的实现:

' '.join(shlex.quote(x) for x in split_command)
Run Code Online (Sandbox Code Playgroud)

https://bugs.python.org/issue22454

  • 这正是Python当前的实现:[3.9/Lib/shlex.py](https://github.com/python/cpython/blob/3.9/Lib/shlex.py) (2认同)

小智 9

它是python 3.8 中的shlex.join()


Lar*_*ngs 6

subprocess用途subprocess.list2cmdline().它不是官方的公共API,但它在subprocess文档中提到,我认为它使用起来非常安全.它比pipes.open()(更好或更坏)更复杂.