I want to parse some simple arguments from the command line. This shows all of the arguments:

#!/usr/bin/python
import sys

#print all of the arguments
for arg in sys.argv:
	print arg

but I want to handle something like

--file a.txt

or

--x 12 --y 13 --z 14

I saw some libraries like optparse, but is there not something built in to do this simple type of parsing?

Thanks,
Dave

I see, I didn't realize that optparse was built in. I'm coming from c++, so almost nothing is built in, and adding libraries is usually pretty annoying.

Also, how do you handle required options? I saw a lot of threads about a philosophical debate of if options can be required, but no information on how to actually use them.

Dave

Also, how do you handle required options? I saw a lot of threads about a philosophical debate of if options can be required, but no information on how to actually use them.

Dave

This is from the optparse doc:

required option
an option that must be supplied on the command-line; note that the phrase “required option” is self-contradictory in English. optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either. See examples/required_1.py and examples/required_2.py in the optparse source distribution for two ways to implement required options with optparse.

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.