Python optparse and spaces in argument

When using optparse, I want to get the whole line after the option, but I only get its part to the first place.

eg:.

python myprog.py --executable python someOtherProg.py 

What I get in "executable" is just "python".

Is it possible to parse such strings with optparse or do you need to use argparse for this?

€: I already tried to include it in the "s". But after further delving into the code, I found that calling the subprocess cannot process the argument.

The command line is populated with the args list.

 args = [self.getExecutable()] + self.getArgs().split() 

Like it

 "[python D:\\\workspace\\\myprog\\\src\\\myprog.py]" 

This gives me the system cannot find the file exception. When i use

 args[0] 

it works. But I lose the arguments in the executable.

The subprocessor module builds cmdline from the list if it does not receive the string in the first place, so I can not explain this behavior at the moment.

+6
python optparse
source share
5 answers

You can enclose them in quotation marks to make them work with existing code.

 python myprog.py --executable "python someOtherProg.py" 

Is it possible to parse such strings with optparse or do you need to use argparse for this?

I do not know how and how you can do this with optparse , since I did not work with optparse .

However, I can help you with argparse . Here is a quick example:

 #!/usr/bin/python import argparse, sys if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'Demonstration of Argparse.') parser.add_argument('-e', '--executable', nargs = '+', help = 'List of executables') args = parser.parse_args(sys.argv[1:]) print args.executable 

And use:

 manoj@maruti :~$ python myprog.py --executable python someOtherProg.py ['python', 'someOtherProg.py'] 

I also recommend switching from optparse to argparse . optparse deprecated since 2.7.

+12
source share

I found another good alternative to shlex - the lexical analyzer class for simple shell syntaxes.

Source link: How to parse command line with regular expressions?

 >>> import shlex >>> shlex.split('"param 1" param2 "param 3"') ['param 1', 'param2', 'param 3'] >>> shlex.split('"param 1" param2 "param 3"') Traceback (most recent call last): [...] ValueError: No closing quotation >>> shlex.split('"param 1" param2 "param 3\\""') ['param 1', 'param2', 'param 3"'] 
+6
source share

The behavior you see is due to the fact that it is your shell, not python, which parses the command line and splits it into sys.argv words. Python is started by the shell via exec () with argv already populated.

Most shells will separate argv elements into spaces unless you tell them not to quote or run away.

Quotes work as described above.

In many shells you can do this:

 python myprog.py --executable python\ someOtherProg.py 

The backslash avoids the next space without requiring quotes.

+4
source share

If you know how many words after the flag you are going to get, you can change the way you create the --executable option in optparse to handle the situation correctly:

Instead of the single word after the option flag, you can set the optparse parser to search for two (or more) words:

 from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", action="store", dest="filename", help="File to be processed.", metavar="FILE") parser.add_option("-e", "--executable", action="store", dest="my_exe", help="Command to be executed", metavar="EXE", nargs=2) 

In this snippet, the -f or --file option expects only one word and saves it as a string (by default) in the filename variable.

Unlike the -e option, --executable two words are expected due to the nargs=2 option. This will cause the two words found behind the -e or --executable flag to be stored as strings in the my_exe Python my_exe .

Check out http://docs.python.org/library/optparse.html for more information on optparse and remember that it was deprecated since 2.7 in favor of argparse .

+4
source share

Just to complete this list of answers if you cannot upgrade to argparse.

Optparse cannot handle these situations (multiple lines). You can use nargs to indicate a certain number of valiables, but there is nothing like "one or more". You need to hack , or use another library (e.g. argparse or another).

+1
source share

All Articles