Claudiu
Claudiu

Reputation: 229421

how to format a shell command line from a list of arguments in python

I have a list of arguments, e.g. ["hello", "bobbity bob", "bye"]. How would I format these so they would be passed appropriately to a shell?

Wrong:

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

Correct:

>>> magic(args)
hello "bobbity bob" bye

Upvotes: 7

Views: 3352

Answers (4)

unutbu
unutbu

Reputation: 879899

You could use the undocumented but long-stable (at least since Oct 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'

Upvotes: 18

mavnn
mavnn

Reputation: 9469

If you're actually sending the values to a shell script, subprocess.popen handles this for you:

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

Otherwise, I believe you're down to string manipulation. shlex.split does the opposite of what you want, but there doesn't seem to be a reverse.

Upvotes: 1

driquet
driquet

Reputation: 679

The easier way to solve your problem is to add \"...\" whenever your text has at least two words.
So to do that :

# 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)

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881663

What's wrong with the old-school approach:

>>> 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 single-word arguments are quoted as well.

Upvotes: 0

Related Questions