getopt make two options mandatory - python

I am using python getopt to parse the arguments that user gives.
try:
options, remainder = getopt.getopt(sys.argv[1:], 'hl:d:r:',
['h','help','lo=','dat=','rel='])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
for opt, arg in options:
if opt in ('-h', '--help'):
usage()
sys.exit()
elif opt == "--lo":
elif opt == "--dat":
elif opt == '--rel':
how can we pair two options together i.e if the user gives --dat option he should definitely provide --rel option or else we exit.
can we do that using getopt?
Thanks

Related

Pytest assert if sys. argv == something it will run a function

I'm trying to test the main function that if len (sys. argv) < 1 or len (sys. argv) < 4 it will run a function using pytest
this is my main fucntion
def main():
if len(sys.argv) == 1:
print(print_help())
elif len(sys.argv) == 2 or len(sys.argv) == 3:
if sys.argv[1] == 'help' or sys.argv[1] == 'h' or sys.argv[1] == 'H':
print(print_help())
else:
print('no such command arguments try python project.py help')
def print_help:
the_help = 'the help section'
return the_help
if __name__ =='__main__':
main()
How can I use pytest to test this main function if sys. argv < 1 that it will run the print_help function
or if sys.argv == 'help' or sys.argv == 'h' or sys.argv == 'H' it will run the same fucntion
My preferred approach is make your main() function take its inputs from a variable instead of from sys.argv directly:
def main(args):
if len(args) == 1:
print(print_help())
elif len(args) == 2 or len(args) == 3:
if args[1] == 'help' or args[1] == 'h' or args[1] == 'H':
print(print_help())
else:
print('no such command arguments try python project.py help')
def print_help:
the_help = 'the help section'
return the_help
if __name__ =='__main__':
main(sys.argv)
Now you can use capsys in your test function to test the output, and can easily pass in whatever list of arguments you want to test without having to patch or mock anything.
Also, argparse does this sort of command line processing for you. I highly, highly recommend using it (or other similar libraries) instead of re-inventing the wheel.
I find some kind of answer that helps a little bit
I find it on this Github link
def test_main(capsys):
from project import main
sys.argv = ['h', 'H', 'help']
main()
out, err = capsys.readouterr()
assert out.startswith("the help section") is True
it check if the output of the print_help is the same as entering one of the commands in sys.argv= ['h', 'H', 'help']

Python commandline parameter not raising error if argument is wrongly used

I have the following Python code that has 1 command line optional parameter (c) that has an argument and 2 options (a and b) that do not have an argument:
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"abc:",["csvfile="])
except getopt.GetoptError:
print 'Error in usage - a does not require an argument'
sys.exit(2)
for opt, arg in opts:
print "Raw input is: {}" .format(opt)
if opt in ("-c", "--csvfile"):
outputfile = arg
print 'Output file is {}' .format(outputfile)
elif opt == '-a':
print 'Alpha'
elif opt == '-b':
print 'Beta'
print 'User choice is {}' .format(opt.lstrip('-'))
if __name__ == "__main__":
main(sys.argv[1:])
When I enter python readwritestore.py -a I get:
Raw input is: -a
Alpha
User choice is a
This is what I was hoping for if the commandline argument is -a. However, if I enter python readwritestore.py -a csvfile_name, then I get:
Raw input is: -a
Alpha
User choice is a
This is not what I intended for. In this function, c is the only option that rquires an argument. If I enter a with an argument,
the code should give the error message that I set up
Error in usage - a does not require an argument
This does not happen for a or b. It is allowing the argument to be entered without raising an error.
If the options that do not require an argument are entered with an argument, then I would like it to raise an error. python readwritestore.py -a text
and python readwritestore.py -b text should raise the error Error in usage - a does not require an argument.
Is there a way to specify this? Is getopt() the correct way to do this?
Additional Information:
I only want python readwritestore.py -c text to work with the argument. For the other 2 options, a and b, the code should raise the error.
checking the size of sys.argv (the list of argument supplied when calling the script) can help you checking that :
import sys
import getopt
def main(argv):
inputfile = ''
outputfile = ''
opts, args = getopt.getopt(argv, "abc:", ["csvfile="])
for opt, arg in opts:
print "Raw input is:", opt
if opt in ("-c", "--csvfile"):
outputfile = arg
print 'Output file is ', outputfile
elif opt == '-a':
if len(sys.argv)=2:
print 'Alpha'
else:
print "incorect number of argument"
elif opt == '-b':
if len(sys.argv)=2:
print 'Beta'
else:
print "incorect number of argument"
print 'User choice is ', opt
if __name__ == "__main__":
main(sys.argv[1:])
I know it's not what you asked (argparse) but here is how you could do it with argparse :
from argparse import *
def main():
parser = ArgumentParser()
parser.add_argument('-c', '--csvfile', help='do smth with cvsfile')
parser.add_argument(
'-a', '--Alpha', help='Alpha', action='store_true')
parser.add_argument(
'-b', '--Beta', help='beta smth', action='store_true')
if args.csvfile:
print 'Output file is {}' .format(args.csvfile)
if args.Alpha:
print 'Alpha'
if args.Beta:
print 'Beta'
if __name__ == "__main__":
main()
It will raise an error is to many argument are supplied. (also python readwritestore.py -h will display the help just like man in unix)

Set external inputs in python program

I want to do something like this in my python code
python my_prog.py -inp 3 -inp2 4
and be able to use inp and inp2 as inputs in my python program. How can I do it?
You're looking for the argparse module.
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('input1', metavar='a', type=int, help='an input for foo')
parser.add_argument('input2', metavar='b', type=int, help='an input for bar')
args = parser.parse_args()
print(args.input1 + args.input2)
You can use getopt for parsing input arguments.
Example from the docu:
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
# ...
if __name__ == "__main__":
main()

command line arguments not being recognised

Im trying to send some command line arguments to a program I've written. I adapted some code I found in a tutorial. However, only the last of the arguments I am sending seam to be getting through. For example, if I type the following in:
python test.py -m A
Nothing happens, however, if I type in:
python test.py -s A
the final argument in the list it seams to work... (code attached below)
import sys, getopt
def main(argv):
mina = ""
capsize= ""
matchcharge= ""
steps= ""
try:
opts, args = getopt.getopt(argv,"m:cs:mc:s:",["min=","capsize=","matchcharge=","steps="])
except getopt.GetoptError:
print("argument not recognised")
sys.exit(2)
for opt, arg in opts:
if opt == ("-m", "--min"):
mina = arg
print("1")
elif opt in ("-cs", "--capsize"):
capsize = arg
print("2")
elif opt in ("-mc", "--matchcharge"):
matchcharge = arg
print("3")
elif opt in ("-s", "--steps"):
steps = arg
print("4")
print("mina " + str(min))
print("capsize" + str(capsize))
print("matchcharge" + str(matchcharge))
print("steps " + str(steps))
if __name__ == "__main__":
main(sys.argv[1:])
In your code you have
if opt == ("-m", "--min"):
which should be
if opt in ("-m", "--min"):
Since you had that right on all the other places, I guess this was just forgotten there.

Filtering integers out of python command line arguments

so I wrote a program and I want to pass it either a filename and an integer or just an integer. Whats the best way to determine which argument is the integer? This is what I have:
import sys
if len(sys.argv) > 1):
for e in sys.argv:
try:
bio = map(e, int)
except:
pass
thanks in advance
You could check whether or not the argument is an integer with the string isdigit() method:
import sys
if len(sys.argv) > 1:
for e in sys.argv:
if e.isdigit():
# all characters in e are digits and there is at least one character in e
else:
# it is possibly your filename argument
But, I should encourage you to give a chance to the argparse library: http://docs.python.org/dev/library/argparse.html
import argparse
parser = argparse.ArgumentParser(description = 'A simple description')
parser.add_argument('-f', action = 'store', dest = 'filename', required = False)
parser.add_argument('-n', action = 'store', dest = 'n', required = True, type=int)
arguments = parser.parse_args()
print arguments.n
print arguments.filename
def isint(val):
try:
int(val)
return True
except:
return False
int_args = filter(isint,sys.argv)
not_int_args = set(sys.argv) - set(int_args)
if len(sys.argv) == 1: #user passed in only one argument. It must be an integer.
bio = int(sys.argv[0])
elif len(sys.argv) == 2: #user passed in two arguments: filename and integer.
filename = sys.argv[0]
bio = int(sys.argv[1])
else: #user didn't pass in the right number of arguments
raise Exception("Expected one or two arguments")

Categories

Resources