When handling command-line arguments, I roughly know getopt will work, but have never used it before. The documents on some books seems not very informative, if read multiple arguments from the command line, is it right to use sys.argv[1], sys.argv[2], etc to assign the arguments to respective variable in the program?
Thanks!

Sounds great! I will take a thorough look at it. Thanks a lot!

I just read the article but still have a couple of questions. In the article, "In this case parse_args() will place all arguments in a tuple. I.e. after we run parse_args(), opt.multi will be a tuple containing all arguments that user has passed to our program."

1. So if I need to get the arguments in the program, can we just use a=opt.multi[1], b=opt.multi[2] etc?
2. If I want to have an optional argument in the end, e.g. without this argument program should proceed another way, is optparse working in this situation?

Thanks a lot!

I just read the article but still have a couple of questions. In the article, "In this case parse_args() will place all arguments in a tuple. I.e. after we run parse_args(), opt.multi will be a tuple containing all arguments that user has passed to our program."

1. So if I need to get the arguments in the program, can we just use a=opt.multi[1], b=opt.multi[2] etc?
2. If I want to have an optional argument in the end, e.g. without this argument program should proceed another way, is optparse working in this situation?

Thanks a lot!

1. tuples are numbered from 0, so it will be opt.multi[0] and opt.multi[1]. Note that one seldom needs options with multiple arguments.
2. If you mean an argument which is not part of an option, your program must examine the content of the list args in opt, args = parser.parse_args() .

Write a few test scripts to experiment with optparse, it's the best way to see how it works.

Thanks! I tried the following code, always got error message "invalid syntax", what is the probelm?

def main(args):
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-M', help='multiple arguments', dest='multi', \
                      action='store', nargs=3)
    (opts, args) = parser.parse_args()

    a=opt.multi[0]
    b=opt.multi[1]
    c=opt.multi[2]

    print "a=", a
    print "b=", b
    print "b=", b

#execute upon command-line invocation
if__name__=="__main__": main(sys.argv)

Thanks! I tried the following code, always got error message "invalid syntax", what is the probelm?

def main(args):
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-M', help='multiple arguments', dest='multi', \
                      action='store', nargs=3)
    (opts, args) = parser.parse_args()

    a=opt.multi[0]
    b=opt.multi[1]
    c=opt.multi[2]

    print "a=", a
    print "b=", b
    print "b=", b

#execute upon command-line invocation
if__name__=="__main__": main(sys.argv)

I corrected your program

def main():
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-M', help='multiple arguments', dest='multi', \
                      action='store', nargs=3)
    (opts, args) = parser.parse_args()

    a=opts.multi[0]
    b=opts.multi[1]
    c=opts.multi[2]

    print "a=", a
    print "b=", b
    print "c=", c

#execute upon command-line invocation
if __name__=="__main__":
    main()

You must debug your program yourself. Python always tell you where the error occurs in the code, so learn to read an exception traceback.

Sorry, I mean when I input the file name and some arguments in command-line mode, the error message is always "invalid syntax".
What I did was I saved the code to the python folder, input >>>commandline.py 1 2 3
then I got syntax error each time. Something I totally missed?
Thanks a lot for your corrections.

Sorry, I mean when I input the file name and some arguments in command-line mode, the error message is always "invalid syntax".
What I did was I saved the code to the python folder, input >>>commandline.py 1 2 3
then I got syntax error each time. Something I totally missed?
Thanks a lot for your corrections.

Please post the traceback. The answer is always in the traceback. Also, if you want to pass arguments to your option -M, you must write commandline.py -M 1 2 3. You should check if opts.multi is None in your code to see if arguments were passed to opts.multi.

There is no syntax error in the code.

Oh. sorry, here is the traceback message,

>>> commandline.py -M 1 2 3
SyntaxError: invalid syntax
>>>

Oh. sorry, here is the traceback message,

>>> commandline.py -M 1 2 3
SyntaxError: invalid syntax
>>>

We probably don't use the same code. Also normally the tracback shows the line where there is the syntax error when there is one. I attach a zip file with the code I'm running.

Thanks for the code, but it is the same, 1 or every first real argument is highlighted. (The version I am using is Python 2.6)

>>> arguments.py -M 1 2 3
SyntaxError: invalid syntax

>>> opts.multi[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
opts.multi[0]
NameError: name 'opts' is not defined
>>>

Thanks for the code, but it is the same, 1 or every first real argument is highlighted. (The version I am using is Python 2.6)

>>> arguments.py -M 1 2 3
SyntaxError: invalid syntax

>>> opts.multi[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
opts.multi[0]
NameError: name 'opts' is not defined
>>>

I understand, you cannot run the script this way from the python shell, you must call the script from an OS shell (cmd shell on windows, terminal in linux or mac).

I also tried on OS shell(cmd on windows), this is the error message I got:

Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'C:\\Python27'
>>> arguments.py -M 1 2 3
File "<stdin>", line 1
arguments.py -M 1 2 3
^
SyntaxError: invalid syntax
Note: "^ " should be under 1 but the format seems not keep after submit.

I also tried on OS shell(cmd on windows), this is the error message I got:

Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'C:\\Python27'
>>> arguments.py -M 1 2 3
File "<stdin>", line 1
arguments.py -M 1 2 3
^
SyntaxError: invalid syntax
Note: "^ " should be under 1 but the format seems not keep after submit.

You must not start the python interactive shell. Simply type python arguments.py -M 1 2 3 in the cmd shell. (Note that your folder C:\Python26 (or other location) must be in your path environment variable).

You are right, I can take the arguments now. Really appreciated. But when I try to set the third arguments optional, (I am thinking using a conditional clause like, if nargs==2, then c=blah, blah, is this the right way to implement?
Thanks a lot!

You are right, I can take the arguments now. Really appreciated. But when I try to set the third arguments optional, (I am thinking using a conditional clause like, if nargs==2, then c=blah, blah, is this the right way to implement?
Thanks a lot!

I don't know, I think it's unsual to have an option with a variable number of arguments. What you could do is an option with a single argument and allow something like

python arguments.py -M 1,2,3,4 # A single argument, since there is no separating space
or
python arguments.py -M "1, 2, 3, 4" # put the arguments in a string to create a single arg.

I know, it is hard. I think yours is a good idea, I will see if I can do it. Thanks!

I know, it is hard. I think yours is a good idea, I will see if I can do it. Thanks!

If I may give an advice, write a command line syntax which is familiar to your users. People should be able to start your program without effort.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.