Thread: Command line

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Command line


    How would i print the number of command line options (minus the program name?

    Seperately, what about reading the first command-line option (again not the program name) and print it to the screen as a string

    ________________________________________________

    and how to read the second command-line option as a floating-point number.
    and if the number is less than zero, print its absolute value.
    If the number is greater than zero, print the string "too big".
    If the number is exactly zero, print the string "zero".
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,696
    Rep Power
    480
    import sys
    print(sys.argv)
    # sys.argv is a list.
    # manipulate it like a list.
    try: float('a string') # convert a string to float
    except: print('whoops! bad arg')

    if n == 0: print('zero')
    elif n < 0: print(abs(n))
    else: print('toooo big!')
    Last edited by b49P23TIvg; March 17th, 2013 at 07:43 AM. Reason: fix formatting
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    The arguments themselves (as strings) are in sys.argv. You should consider using the standard library argparse module though, which handles a lot of the work of dealing with command line arguments for you.

    Edit: Here's your example with argparse.
    Code:
    import argparse
    
    
    parser = argparse.ArgumentParser(
        description="Print a thing and do stuff with a number.")
    parser.add_argument("foo", help="the thingy to print")
    parser.add_argument("bar", help="the number to do stuff with", type=float)
    
    
    args = parser.parse_args()
    print(args.foo)
    if args.bar < 0:
        print(-args.bar)
    elif args.bar > 0:
        print("too big")
    else:
        print("zero")
    This does nice things like, for example, creating a help message for you if you call your script with a -h flag:
    Code:
    usage: argparse_example.py [-h] foo bar
    
    Print a thing and do stuff with a number.
    
    positional arguments:
      foo         the thingy to print
      bar         the number to do stuff with
    
    optional arguments:
      -h, --help  show this help message and exit
    Last edited by Nyktos; March 17th, 2013 at 01:01 PM.

IMN logo majestic logo threadwatch logo seochat tools logo