Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse argument with quotes

Is there any way I can tell argparse to not eat quotation marks?

For example, When I give an argument with quotes, argparse only takes what's inside of the quotes as the argument. I want to capture the quotation marks as well (without having to escape them on the command line.)

pbsnodes -x | xmlparse -t "interactive-00"

produces

interactive-00

I want

"interactive-00"
like image 528
denvaar Avatar asked Oct 31 '12 23:10

denvaar


People also ask

What does argparse do in Python?

The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

How do I define an argument in argparse?

Back to argparse, here is how to define an argument. First, we import argparse. Then, we define the parser as shown on line 3. We will talk about that description argument in a minute. Afterward, we add the arguments we want as shown on line 6.

How do I parse a command line argument in Python?

There are many ways to parse command-line arguments passed to a Python program, and using argparse is probably the easiest of them all. So, now you can now define and parse command-line arguments in Python, and also add a nice helpful help message to your program.

What is the difference between nargs and @argumentparser objects?

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action. The supported values are:


2 Answers

I think it is the shell that eats them, so python will actually never see them. Escaping them on the command line may be your only option.

If it's the \"backslash\" style escaping you don't like for some reason, then this way should work instead:

pbsnodes -x | xmlparse -t '"interactive-00"'
like image 142
wim Avatar answered Oct 10 '22 19:10

wim


Command line is parsed into argument vector by python process itself. Depending on how python is built, that would be done by some sort of run-time library. For Windows build, that would be most likely MS Visual C++ runtime library. More details about how it parses command line can be found in Visual C++ documentation: Parsing C++ command-Line arguments.

In particular:

  • A string surrounded by double quotation marks ("string") is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.

  • A double quotation mark preceded by a backslash (\") is interpreted as a literal double quotation mark character (").

If you want to see unprocessed command line, on Windows you can do this:

import win32api
print(win32api.GetCommandLine())
like image 1
il--ya Avatar answered Oct 10 '22 19:10

il--ya