Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 433
Claudiu Avatar asked Aug 25 '11 14:08

Claudiu


People also ask

How do you access command line arguments in Python?

To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.

What list in Python contains arguments passed to a script?

The sys module exposes an array named argv that includes the following: argv[0] contains the name of the current Python program. argv[1:] , the rest of the list, contains any and all Python command line arguments passed to the program.

How do you give a Python script a command line input?

If so, you'll need to use the input() command. The input() command allows you to require a user to enter a string or number while a program is running. The input() method replaced the old raw_input() method that existed in Python v2. Open a terminal and run the python command to access Python.


2 Answers

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'
like image 97
unutbu Avatar answered Sep 19 '22 00:09

unutbu


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)
like image 37
driquet Avatar answered Sep 19 '22 00:09

driquet