LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-18-2010, 08:28 PM   #1
MTK358
LQ 5k Club
 
Registered: Sep 2009
Posts: 6,443
Blog Entries: 3

Rep: Reputation: 723Reputation: 723Reputation: 723Reputation: 723Reputation: 723Reputation: 723Reputation: 723
Python argparse question


How do you implement programs where you can specify an operation as the first argument, and all the other arguments depend on the operation?

Is this possible with Python argparse?

If you don't know what I'm talking about, think of commands like "apt-get install" or "git branch".
 
Old 12-18-2010, 09:50 PM   #2
kbp
Senior Member
 
Registered: Aug 2009
Posts: 3,790

Rep: Reputation: 653Reputation: 653Reputation: 653Reputation: 653Reputation: 653Reputation: 653
The logic to interpret the arguments will be part of your script, I usually use getopt though ...

Code:
import getopt

def main():
  try:
    opts, args = getopt.getopt(sys.argv[1:], "s:t:h", ["source=",target=", "help"])
  except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
  for opt, arg in opts:
    if opt in ("-s", "--source"):
      source = arg
    elif opt in ("-t", "--target"):
      target = arg
    elif opt == '-h':
      usage()
      sys.exit()
    else:
      assert False, "Invalid option"

# put arg validation logic here
cheers
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
python question kpachopoulos Programming 1 09-10-2007 08:06 AM
Python question gamehack Programming 5 01-03-2005 05:21 AM
python question ywchen2000 Programming 1 04-20-2004 11:46 PM
A Python question gamehack Programming 2 03-17-2004 09:09 PM
Python question m4rccd Programming 1 08-24-2003 06:04 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:49 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration