What is the reverse side of shlex.split?

How can I cancel shlex.split results? That is, how can I get a quoted string that "resembles the version of the Unix shell" , given the list strings I want to quote

Update0

I discovered a Python error and made the corresponding function requests here .

+38
source share
6 answers

Now we (3.3) have a shlex.quote function. Its none other that pipes.quote not being moved and not documented (code using pipes.quote will work). See http://bugs.python.org/issue9723 for a full discussion.

subprocess.list2cmdline is a private function that should not be used. However, it could be ported to shlex and officially published. See also http://bugs.python.org/issue1724822 .

+26
source

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

.

+19
source

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

+6
source

There is a request to add shlex.join() that will do exactly what you ask. At the moment, there seems to be no progress on this, although mainly because it will be mostly just forward to shlex.quote() . The bug report mentions a proposed implementation:

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

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

+3
source

Both 'foo' and "'foo'" converted by shlex.split to the same list:

 In [44]: shlex.split("'foo'") Out[44]: ['foo'] In [45]: shlex.split("foo") Out[45]: ['foo'] 

Therefore, I do not think that in all cases you can undo shlex.split , but this can close you:

 In [20]: import subprocess In [21]: subprocess.list2cmdline(shlex.split('prog -s "foo bar"')) Out[21]: 'prog -s "foo bar"' In [22]: subprocess.list2cmdline(shlex.split('prog -s "foo bar" "baz"')) Out[22]: 'prog -s "foo bar" baz' 
+2
source

This is shlex.join () in Python 3.8

0
source

Source: https://habr.com/ru/post/1444897/


All Articles