Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get command line arguments as string

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

like image 951
KocT9H Avatar asked Jun 06 '16 12:06

KocT9H


People also ask

How do you convert an argument to a string?

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.

Are command line arguments 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.

How do I get command line arguments?

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.

Are command line arguments strings C++?

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.


2 Answers

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.

like image 96
cxw Avatar answered Oct 31 '22 02:10

cxw


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:]))
like image 20
szali Avatar answered Oct 31 '22 02:10

szali