7 Replies - 55074 Views - Last Post: 20 July 2010 - 11:57 AM Rate Topic: -----

#1 cronos4d  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-May 08

using getopt() in python

Posted 28 May 2008 - 10:22 AM

I am a new to python and I am trying to create a script that accepts UNIX-style command line options. For example: myapp --help --execute --dothis --dothat

I see that there is a module for this call getopt http://docs.python.o...ule-getopt.html
Although I am having a bit of trouble understanding the syntax.

take this code for example:

import getopt, sys

def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
	except getopt.GetoptError, 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"
def usage():
	   #enter usage here

if __name__ == "__main__":
	main()



What I don't understand is how opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) is used.
Can someone explain the syntax for this?

Is This A Good Question/Topic? 0
  • +

Replies To: using getopt() in python

#2 Nova Dragoon  Icon User is offline

  • The Innocent Shall Suffer, Big Time
  • member icon

Reputation: 36
  • View blog
  • Posts: 6,169
  • Joined: 16-August 01

Re: using getopt() in python

Posted 28 May 2008 - 02:33 PM

opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])

on the left hand side. it looks like getopt.getopt will return a tuple, this will split the tuple across these two variables.

Something similar is a,b = (1,2) a will equal 1, and b will equal 2.


On the right hand side in the argument list,

first argument is the arguments passed into your program starting at array index 1 and to the end of the argument list. Index 0 is left out as that is the name of the program

second argument:
options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon

third argument:
long_options, if specified, must be a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ("=").


so what you have setup are options for -h, -o with an argument, and -v. and long options --help and --output with an argument.
Was This Post Helpful? 1

#3 linuxunil  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 46
  • Joined: 07-March 06

Re: using getopt() in python

Posted 14 June 2008 - 09:38 AM

What I don't understand is how opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) is used.
Can someone explain the syntax for this?
[/quote]

They are the long and short flags for that program. 'h' would be -h 'o' would be -o (the : tells us that it excepts an argument) and 'v' is -v. The next part '["help", "output="]' basically says the same thing. "help" is the --help flag, "output=" is the --output flag that has one argument.

So you could launch the program with '-h -o output.txt -v' or '--help --output output.txt -v' (notice since -v has no -- or long opt declared it can't be used.

Here is another example I made:
import getopt, sys, os

def main(argv):
    try:
        opt, args = getopt.getopt(argv, "he:da:", ["help", "execute=", "dothis", "argument="])
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opt:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-e", "--execute"):
            os.system(a)
        elif o in ("-d", "--dothis"):
            print "dothis"
        elif o in ("-a", "--argument"):
            print str(a)
        else:
            assert False, "unhandled option"
def usage():
    usage = """
    -h --help                 Prints this
    -e --execute (cmd)        Execute a system command
    -d --dothis               Print dothis
    -a --argument (argument   Print (argument)
    """
    print usage

if __name__ == "__main__":
    main(sys.argv[1:]) # [1:] slices off the first argument which is the name of the program


copy and save as example.py
On any Unixy machine you can run something like "python example.py --execute ls" etc.
On windows (I haven't tested) you can run "python example.py --execute dir" etc
Was This Post Helpful? 0
  • +
  • -

#4 cronos4d  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-May 08

Re: using getopt() in python

Posted 14 June 2008 - 04:06 PM

View Postlinuxunil, on 14 Jun, 2008 - 09:38 AM, said:

What I don't understand is how opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) is used.
Can someone explain the syntax for this?


They are the long and short flags for that program. 'h' would be -h 'o' would be -o (the : tells us that it excepts an argument) and 'v' is -v. The next part '["help", "output="]' basically says the same thing. "help" is the --help flag, "output=" is the --output flag that has one argument.

So you could launch the program with '-h -o output.txt -v' or '--help --output output.txt -v' (notice since -v has no -- or long opt declared it can't be used.

Here is another example I made:
import getopt, sys, os

def main(argv):
    try:
        opt, args = getopt.getopt(argv, "he:da:", ["help", "execute=", "dothis", "argument="])
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opt:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-e", "--execute"):
            os.system(a)
        elif o in ("-d", "--dothis"):
            print "dothis"
        elif o in ("-a", "--argument"):
            print str(a)
        else:
            assert False, "unhandled option"
def usage():
    usage = """
    -h --help                 Prints this
    -e --execute (cmd)        Execute a system command
    -d --dothis               Print dothis
    -a --argument (argument   Print (argument)
    """
    print usage

if __name__ == "__main__":
    main(sys.argv[1:]) # [1:] slices off the first argument which is the name of the program


copy and save as example.py
On any Unixy machine you can run something like "python example.py --execute ls" etc.
On windows (I haven't tested) you can run "python example.py --execute dir" etc
[/quote]

the part I don't understand is the sys.argv[1:] -> why is this being passed to getopt() as the first argument?
Was This Post Helpful? 0
  • +
  • -

#5 linuxunil  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 46
  • Joined: 07-March 06

Re: using getopt() in python

Posted 15 June 2008 - 05:55 PM

Quote

What I don't understand is how opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) is used.
Can someone explain the syntax for this?


Ok lets break it down,
opt, args is splitting the output of getopts into two list, the first value goes into opt, the sencond into args, the third into opt, the fourth in to args, and so on.

sys.argv is where the interpreter stores the arguments for your program by default. They are stored as alist and [1:] slices the first argument off (which is the name of your program)

'ho:v'
the h is declaring the '-h' command line argument.
o: is declaring that you have a '-o' argument that it's self takes and argument (-o value)
and v is delaring '-v'

["help","output="]
"help" equals out to --help
and "output=" is --output (value) just like -o (value)

Also if your really interested I would pick up a copy of Dive into Python. It's a really good book that covers this and many other python fundamentals in depth.
Was This Post Helpful? 0
  • +
  • -

#6 cronos4d  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 16-May 08

Re: using getopt() in python

Posted 16 June 2008 - 12:11 PM

View Postlinuxunil, on 15 Jun, 2008 - 05:55 PM, said:

Quote

What I don't understand is how opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) is used.
Can someone explain the syntax for this?


Ok lets break it down,
opt, args is splitting the output of getopts into two list, the first value goes into opt, the sencond into args, the third into opt, the fourth in to args, and so on.

sys.argv is where the interpreter stores the arguments for your program by default. They are stored as alist and [1:] slices the first argument off (which is the name of your program)

'ho:v'
the h is declaring the '-h' command line argument.
o: is declaring that you have a '-o' argument that it's self takes and argument (-o value)
and v is delaring '-v'

["help","output="]
"help" equals out to --help
and "output=" is --output (value) just like -o (value)

Also if your really interested I would pick up a copy of Dive into Python. It's a really good book that covers this and many other python fundamentals in depth.


This make sense, until I try to add more arguments.

import getopt, sys

#define admin server hostname
global adminServer 
adminServer = '\'myAdminServer1\''

def main():
	try:
		opts = getopt.getopt(sys.argv[1:], "ho:c:", ["help", "server=", "command="])
	except getopt.GetoptError, 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 in ("-h", "--help"):
			usage()
			sys.exit()
		elif o in ("-s", "--server="):
		server = a
		print "manager server is",  server
	elif o in ("-c", "--command="):
		command = a
		print "command is ", command
		else:
			assert False, "unhandled option : 207"

def usage():
		print "jvm_controller.py usage: -h help --server=<managed_server_name> --command=<command>"
	print server

def connect():
	connect('appuser','appuser','t3://myAdminServer1:7001')

def shutdown_mgdServer():
	shutdown('server')

def start_mgdServer():
	start('server')

if __name__ == "__main__":
		main()




throws the following error:

 python test.py -h
Traceback (most recent call last):
  File "test.py", line 44, in <module>
	main()
  File "test.py", line 17, in main
	for o, a in opts:
ValueError: need more than 1 value to unpack




so I modified the getopts to read
 opts = getopt.getopt(sys.argv[1:], "ho:c:", ["help", "server=", "command="])



I want to add the --command=parameter.

getopt parses the sys.argv[1:] as a string, so I shouldn't have to modify anything there.
I am not sure why this code is failing when I try to add a new command line option.

Thanks in advance.
Was This Post Helpful? 0
  • +
  • -

#7 linuxunil  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 46
  • Joined: 07-March 06

Re: using getopt() in python

Posted 17 June 2008 - 07:28 AM

There are a few syntactic and semantical errors in your program. Make sure what you have is indented properly, what you posted wasn't. Also when you do if o in ("-s", "--server="): it should be if o in ("-s", "--server"): same with the "-c" option. It would be easier to just have
 
for o,a in opts:
        if o in ("-s", "--server"):
            server = a
            print "Manager server is", server
        elif o in ("-c", "--comand"):
            command = a
            print "Command is" , command
        else:
            usage()
            sys.exit()



This will still print out usage for the -h and --help option but it will also print out the usage if some one specifies an invalid parameter. This will make it clearer to the user what went wrong than some ambiguous error code. Error codes should generally only be used when something goes wrong due to a bug in the program, not user error. It will save you a lot of tech support headaches if anyone else ever uses your program.

You can't print server in the usage definition because it is out of it's scope. It doesn't know what it is.

You might be better off to create a server class that holds these values and had defaults instead of declaring something like global adminserver this is generally considered bad programming practice.

You could implement the class as such (Note: This is not a working class just and example)

class Server:
    def __init__(self, adminserver="myadminserver1"):
        self.adminserver = adminserver

    def connect(self):
        pass # Pass  does nothing add your code here to connect
    def shudown_mgd_server(self): # It is considered good practice to use either '_' to separate words or capitalize each word,    
        pass                                    # but not a mixture of both
    def start_mgdServer(self):        # This is confusing to anyone else using your code and maybe even you later on. 
        pass



For more info and alot of other stuff check out Dive into Python it covers classes and a lot more.
Was This Post Helpful? 0
  • +
  • -

#8 Guest_WakeUpHuck*


Reputation:

Re: using getopt() in python

Posted 20 July 2010 - 11:57 AM

Use just sys.argv instead of sys.argv[1:] for wsadmin.sh -lang jython.
Was This Post Helpful? 0

Page 1 of 1