What's the reverse of shlex.split?

后端 未结 5 1713
孤独总比滥情好
孤独总比滥情好 2020-12-08 02:16

How can I reverse the results of a shlex.split? That is, how can I obtain a quoted string that would \"resemble that of a Unix shell\", given a list of strings

相关标签:
5条回答
  • 2020-12-08 02:38

    We now (3.3) have a shlex.quote function. It’s none other that pipes.quote moved and documented (code using pipes.quote will still work). See http://bugs.python.org/issue9723 for the whole discussion.

    subprocess.list2cmdline is a private function that should not be used. It could however be moved to shlex and made officially public. See also http://bugs.python.org/issue1724822.

    0 讨论(0)
  • 2020-12-08 02:38

    subprocess uses subprocess.list2cmdline(). It's not an official public API, but it's mentioned in the subprocess documentation and I think it's pretty safe to use. It's more sophisticated than pipes.open() (for better or worse).

    0 讨论(0)
  • 2020-12-08 02:39

    There is a feature request for adding shlex.join(), which would do exactly what you ask. As of now, there does not seem any progress on it, though, mostly as it would mostly just forward to shlex.quote(). In the bug report, a suggested implementation is mentioned:

    ' '.join(shlex.quote(x) for x in split_command)
    

    See https://bugs.python.org/issue22454

    0 讨论(0)
  • 2020-12-08 02:46

    How about using 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'"
    

    .

    0 讨论(0)
  • 2020-12-08 02:47

    It's shlex.join() in python 3.8

    0 讨论(0)
提交回复
热议问题