March 15th, 2013, 03:02 PM
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".
March 15th, 2013, 06:33 PM
# 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] are essential for python code and Makefiles!
March 16th, 2013, 10:36 PM
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.
This does nice things like, for example, creating a help message for you if you call your script with a -h flag:
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 args.bar < 0:
elif args.bar > 0:
usage: argparse_example.py [-h] foo bar
Print a thing and do stuff with a number.
foo the thingy to print
bar the number to do stuff with
-h, --help show this help message and exit
Last edited by Nyktos; March 17th, 2013 at 01:01 PM.