Thread: Command line

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

    Join Date
    Mar 2013
    Rep Power

    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 God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Rep Power
    import sys
    # 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
    Rep Power
    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.
    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()
    if < 0:
    elif > 0:
        print("too big")
    This does nice things like, for example, creating a help message for you if you call your script with a -h flag:
    usage: [-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