argv
- In the previous homework, the program must
prompt users to input the year and the month.
- It is also possible for a user to supply that information at the
command-line, for example, by typing "python cal.py 2014 11".
- Python can retrieve the command-line arguments via the variable
sys.argv.
Please note that the script name is argv[0]. For example, in the
example "python cal.py 2014 11",
- argv[0] = "cal.py"
- argv[1] = "2014"
- argv[2] = "11"
- To know how many arguments are passed to your program, you may apply
the len() function on sys.argv.
- Let argc denote the count of arguments. Modify your previous homework so that
- if argc == 3:
- Get year from sys.argv[1]
- Get month from sys.argv[2]
- if argc == 1
- Prompt the user to input YYYY.MM
- # This is the same as the original program.
- else
- Print a message to tell users the expected number of
arguments.
The program may run as follows:
$ python cal2.py 2014 11
November 2014
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30