Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Mona Jalal
Mona Jalal
4,302 Points

Can someone please explain in very simple terms what does getopt do here?

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

Very much confused what happens in this line >>> optlist, args = getopt.getopt(args, 'abc:d:')

Is there a team tree house video that covers getopt? It is a very handy feature and I have been asked for it at least in two of my interviews.

Matthew Hill
Matthew Hill
7,799 Points

Hi Mona, I know this doesn't fully answer your question so I'm just putting it as a comment, but the python docs have a fairly straightforward answer here: https://docs.python.org/3.1/library/getopt.html

1 Answer

Steven Parker
Steven Parker
231,269 Points

Hi again Mona, It looks like you're already familiar with the documentation since you quoted the example from it.

The simple explanation is that it breaks up command line contents into option/value pairs along with a list of non-option arguments. This is useful for implementing non-graphic console utility programs.