Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reverse of shlex.split?

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 I wish quoted?

Update0

I've located a Python bug, and made corresponding feature requests here.

like image 436
Matt Joiner Avatar asked Jan 20 '11 14:01

Matt Joiner


People also ask

What is Shlex split?

The shlex module defines the following functions: shlex. split (s, comments=False, posix=True) Split the string s using shell-like syntax. If comments is False (the default), the parsing of comments in the given string will be disabled (setting the commenters attribute of the shlex instance to the empty string).

What does Shlex quote do?

shlex. quote() escapes the shell's parsing, but it does not escape the argument parser of the command you're calling, and some additional tool-specific escaping needs to be done manually, especially if your string starts with a dash ( - ).


2 Answers

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.

like image 93
merwok Avatar answered Oct 02 '22 08:10

merwok


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'" 

.

like image 38
tokland Avatar answered Oct 02 '22 09:10

tokland