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
Related
How can I generate an error message if fewer than required optional arguments are passed in the command line while using argparse in code? for example, I have 5 optional arguments and I want to generate an error message if fewer than 4 optional arguments are used at any time.
My beginner brain can't figure this out.
import argparse
import math
parser = argparse.ArgumentParser(description='Loan Calculator')
parser.add_argument('--type', type=str)
parser.add_argument('--principal', type=int)
parser.add_argument('--periods', type=int)
parser.add_argument('--interest', type=float)
parser.add_argument('--payment', type=int)
args = parser.parse_args()
This is something that's most simply handled after you've called parse_args. Count how many of the options still have the default value of None. If there's more than 1, raise an error.
args = parser.parse_args()
if 1 < sum(1 for x in [args.type, args.principal, args.periods, args.interest, args.payment] if x is None):
sys.exit("Too few options specified")
I am using the argparse library but for whatever reason I'm having difficult printing the -h argument. Here is the entire source I have:
# df.py
import argparse
parser = argparse.ArgumentParser(description='Dedupe assets in our library.')
parser.add_argument('--masters', nargs='?', default=None, type=int, help='Enter one or more ids.')
if __name__ == '__main__':
print ('hi')
I was under the impression that entering in the --h flag via:
$ python df.py --help
Would automatically print the help stuff for the file using argparse but I seem to be making false assumptions. It seems like I also have to add in something like this into my code?
if '--help' in sys.argv: print (parser.parse_args(['-h']))
What is the 'proper' way to print out the help args when using the argparse library?
You forgot to actually parse the arguments; if you put parser.parse_args() in after defining the parser, it would respond to -h/--help. Typically, you'd do something like:
args = parser.parse_args()
so that the args object can be used to access the parsed argument data.
I'll also note that the argument parsing should almost certainly be controlled by the if __name__ == '__main__': guard; if you're not being invoked as the main script, parsing the command line is unusual, to say the least. Idiomatic code would look something like:
# df.py
def main():
import argparse # Could be moved to top level, but given it's only used
# in main, it's not a terrible idea to import in main
parser = argparse.ArgumentParser(description='Dedupe assets in our library.')
parser.add_argument('--masters', nargs='?', type=int, help='Enter one or more ids.')
args = parser.parse_args()
print ('hi')
# Do something with args.masters or whatever
if __name__ == '__main__':
main()
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])
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)