How to format shell command line from argument list in python

I have a list of arguments, for example. ["hello", "bobbity bob", "bye"] . How do I format them so that they are appropriately passed to the shell?

Wrong

 >>> " ".join(args) hello bobbity bob bye 

Right

 >>> magic(args) hello "bobbity bob" bye 
+4
source share
4 answers

You can use an undocumented, but long-term (at least since October 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' 
+12
source

An easier way to solve your problem is to add \ "... \" whenever your text has at least two words.
To do this:

 # 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) 
+1
source

If you really send the values โ€‹โ€‹to the shell script, subprocess.popen processes this for you:

http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen

Otherwise, I suppose you can handle string manipulation. shlex.split does the opposite of what you want, but there seems to be no converse.

+1
source

What is bad about the old school:

 >>> 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 one-word arguments are quoted.

0
source

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


All Articles