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
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.
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.
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.
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'
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With