How can I use parser options in raw_input.
I'll give an example:
import optparse
import win32ui
a = raw_input('Message box')
parser = optparse.OptionsParser()
parser.add_options('-t', dest='title', type='string')
parser.add_options('-m', dest='message', type='string')
(options, args) = parser.parse_args()
title = options.title
message = options.message
win32ui.MessageBox(message, title, 0)
When I enter for example -t hello -m how are you, I want a message box to appear with these options.
How can I solve this please and thanks.
To start with, it's best to not use optparse as this is now a deprecated module, and you should prefer argparse instead.
By default argparse will parse the command-line input
(sys.argv[1:]) - however you can pass it a list of variables to parse instead, e.g.:
import argparse
parser = argparse.ArgumentParser()
parser.parse_args(["-t hello -m how are you"])
So in your specific case you can do:
(options, args) = parser.parse_args([a])
Of course if you have to use optparse then it's almost the same:
import optparse
parser = optparse.OptionParser()
(options, args) = parser.parse_args([a])
Related
I wrote a custom submodule to reuse the same code in my similar API projects.
In my submodule, I have the following:
# sub.py
from argparse import ArgumentParser
arg_parser = ArgumentParser()
arg_parser.add_argument("-s", "--silent", help="silent mode", action="store_true")
script_args = arg_parser.parse_args()
if not script_args.silent:
# If the silent flag isn't passed then add logging.
#logger.addHandler(console_handler)
What's the best way to add additional arguments via add_argument() in my main script?
# main.py
import sub
# This still works:
if sub.script_args.silent:
# Some code
# I tried this, but it doesn't work:
sub.arg_parser.add_argument("-t", "--test", help="test mode", action="store_true")
sub.script_args.parse_args()
# The script doesn't know about -t.
You can use parse_known_args function (partial parsing).
For example:
# sub.py
from argparse import ArgumentParser
arg_parser = ArgumentParser()
arg_parser.add_argument("-s", "--silent", help="silent mode", action="store_true")
partial_script_args = arg_parser.parse_known_args()[0]
print("silent") if partial_script_args.silent else print("not silent")
# main.py
import sub
# This still works:
if sub.partial_script_args.silent:
pass
sub.arg_parser.add_argument("-t", "--test", help="test mode", action="store_true")
full_script_args = sub.arg_parser.parse_args()
print("test") if full_script_args.test else print("not test")
Note the warning in the documentation:
Warning: Prefix matching rules apply to parse_known_args(). The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.
My Python script:
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--l', nargs='+', help='list = [title, HTML]')
args = parser.parse_args()
print args.l
When I execute the script inside Keyboard Maestro, I do it like this:
python ~/Desktop/save_html.py -l $KMVAR_javascriptTITLE
It's working, but argparse is parsing anything with a space.
First Name turns into ['First', 'Last']. If I understand it correctly, arparse is reading my command like:
python ~/Desktop/save_html.py -l First Last
when what I really want is:
python ~/Desktop/save_html.py -l "First Last"
How do I pass a variable into argparse and it reads it as 1 string?
Changing my comment to an answer
How about if you do python ~/Desktop/save_html.py -l "$KMVAR_javascriptTITLE"? escape the quotes if necessary
You could use a CustomAction to do this:
import os
import argparse
class CustomAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, " ".join(values))
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--l', action=CustomAction, type=str, nargs='+', help='list = [title, HTML]')
args = parser.parse_args()
print args.l
I would like to have an option -n, that will allow users to specify a size of a list. The default will be 30. So:
./findNumberOfPlayers.py -n10
I haven't done any command line arguments with python before but am confused with how to include -n10 within the program. I understand I would import sys and have 12 assigned to sys.argv[1] but how does it work with -n10?
Thank You! I appreciate the help.
Use argparse.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", help="Enter a number", type=int)
You can then access the arg like this -
args = parser.parse_args()
num_players = args.number if args.number else 30
I am using optparse to get command line input.
Lets say that I am running a script demo.py and it creates some output. But unless I specify the command line input, the output is not written to a file.
I am trying to do the following:
python demo.py in command line should run the script, but not write the output anywhere.
python demo.py -o in command line should write the output to my default file name output.txt.
python demo.py -o demooutput.txt in command line should write the output to file demooutput.txt.
PS: I would not prefer to switch to argparse from optparse.
You can use optparse-callbacks to achieve this.
Here is how it wiill work for your use case.
parser.add_option("-o", action="callback", dest="output", callback=my_callback)
def my_callback(option, opt, value, parser):
if len(parser.rargs) > 0:
next_arg = parser.rargs[0]
if not next_arg.startswith("-"):
# Next argument is not another option
del parser.rargs[0]
setattr(parser.values, option.dest, next_arg)
return
# If not processed, set the default value
setattr(parser.values, option.dest, "output.txt")
I don't think there is unfortunately - the only way I can think of is hacking around the problem by adding your own logic statements. The following code should do the trick.
import re, sys
import optparse from OptionParser
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
if '-f' in argv:
a = argv.index('-f')
if (a != len(argv)-1) and re.search('[.]txt', argv[a+1]):
parser.add_option("-f", "--foo", dest="foo")
else:
parser.add_option("-f", dest="foo", action="store_true")
This doesn't answer the direct question, 'how to define an Action...', but it handles the inputs in a simple way.
Set '-o' to be 'store_true'. If True check the 'args' variable for a file name.
(options, args) = parser.parse_args()
if options.o:
if args:
dest = args[0]
else:
dest = 'output.txt'
else:
dest = ''
(In argparse the equivalent would be to define a positional argument with nargs='?'.)
If these are the only arguments, you could also get by with checking for the filename without requiring the `-o'.
Another possibility - 'store_const', with the positional 'filename' having priority:
parser = optparse.OptionParser()
parser.add_option('-o',dest='dest',action='store_const', const='output.txt', default='')
(options, args) = parser.parse_args()
if args:
options.dest = args[0]
print options
write a script that takes two optional boolean arguments,"--verbose‚" and ‚"--live", and two required string arguments, "base"and "pattern". Please set up the command line processing using argparse.
This is the code I have so far for the question, I know I am getting close but something is not quite right. Any help is much appreciated.Thanks for all the quick useful feedback.
def main():
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('base', type=str)
parser.add_arguemnt('--verbose', action='store_true')
parser.add_argument('pattern', type=str)
parser.add_arguemnt('--live', action='store_true')
args = parser.parse_args()
print(args.base(args.pattern))
The string arguments are not required by default, so you need to state that. Also the print statement that uses the arguments is incorrect.
#!/usr/bin/python
import argparse
if __name__=="__main__":
parser = argparse.ArgumentParser(description='eg $python myargs.py --base arg1 --pattern arg2 [--verbose] [--live]')
parser.add_argument('--base', required=True, type=str)
parser.add_argument('--pattern', required=True, type=str)
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--live', action='store_true')
args = parser.parse_args()
print "args.base=" + str(args.base)
print "args.pattern=" + str(args.pattern)
print "args.verbose=" + str(args.verbose)
print "args.live=" + str(args.live)
the #!/usr/bin/python at the top enables the script to be called directly, though python must be located there (to confirm, type $which python), and you must set the file to have execute permission ($chmod +x myargs.py)