0

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:])
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the advice, I made that change, however, the code still dosen't work. if I put in the following argument (for example) "test.py -m min -cs cs -mc mc -s s". min gets set to "c" and steps get set to "cs". Is there anything else I'm doing wrong here?
You need to make cs and mc also long flags. Currently "m:cs:mc:s:" means that for arguments m, s, c and s there should be attributes but c and m can be used such as.
Take a look at the docs docs.python.org/2/library/getopt.html I would also recommend using argparse docs.python.org/2/library/argparse.html#module-argparse for easier command-line arguments processing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.