Join 132,683 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,234 people online right now. Registration is fast and FREE... Join Now!
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
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?
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.
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:
python
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 name='linuxunil' date='14 Jun, 2008 - 09:38 AM' post='369786'] 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:
python
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?
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.
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.
CODE
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
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
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.
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
Python
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)
Python
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.