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
Python has a built-in function str() which converts the passed argument into a string format. The str() function returns a string version of an object. The object can be int , char , or a string . If the object is not passed as an argument, then it returns an empty string.
Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument.
If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.
The length of this array is argc. Argument 0 is the path and name of the current program being run. Argument 1 and 2 in this case are the two command line parameters we passed in. Command line arguments are always passed as strings, even if the value provided is numeric in nature.
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.
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:]))
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