Reputation: 349
I want to print all command line arguments as a single string. Example of how I call my script and what I expect to be printed:
./RunT.py mytst.tst -c qwerty.c
mytst.tst -c qwerty.c
The code that does that:
args = str(sys.argv[1:])
args = args.replace("[","")
args = args.replace("]","")
args = args.replace(",","")
args = args.replace("'","")
print args
I did all replaces because sys.argv[1:] returns this:
['mytst.tst', '-c', 'qwerty.c']
Is there a better way to get same result? I don't like those multiple replace calls
Upvotes: 22
Views: 66445
Reputation: 518
None of the previous answers properly escape all possible arguments, like empty args or those containing quotes. The closest you can get with minimal code is to use shlex.quote (available since Python 3.3):
import shlex
cmdline = " ".join(map(shlex.quote, sys.argv[1:]))
EDIT
Here is a Python 2+3 compatible solution:
import sys
try:
from shlex import quote as cmd_quote
except ImportError:
from pipes import quote as cmd_quote
cmdline = " ".join(map(cmd_quote, sys.argv[1:]))
Upvotes: 23
Reputation: 13257
The command line arguments are already handled by the shell before they are sent into sys.argv
. Therefore, shell quoting and whitespace are gone and cannot be exactly reconstructed.
Assuming the user double-quotes strings with spaces, here's a python program to reconstruct the command string with those quotes.
commandstring = '';
for arg in sys.argv[1:]: # skip sys.argv[0] since the question didn't ask for it
if ' ' in arg:
commandstring+= '"{}" '.format(arg) ; # Put the quotes back in
else:
commandstring+="{} ".format(arg) ; # Assume no space => no quotes
print(commandstring);
For example, the command line
./saferm.py sdkf lsadkf -r sdf -f sdf -fs -s "flksjfksdkfj sdfsdaflkasdf"
will produce the same arguments as output:
sdkf lsadkf -r sdf -f sdf -fs -s "flksjfksdkfj sdfsdaflkasdf"
since the user indeed double-quoted only arguments with strings.
Upvotes: 13
Reputation: 107
You're getting a list object with all of your arguments when you use the syntax [1:]
which goes from the second argument to the last. You could run a for each loop to join them into one string:
args = sys.argv[1:]
result = ''
for arg in args:
result += " " + arg
Upvotes: 2
Reputation: 17051
An option:
import sys
' '.join(sys.argv[1:])
The join()
function joins its arguments by whatever string you call it on. So ' '.join(...)
joins the arguments with single spaces (' '
) between them.
Upvotes: 31