I have gone through the sys
documentation, however there is something that is still unclear to me. I have looked for some similar question on stackoverflow, but I haven't find anything useful (clearly any reference is appreciated!).
I want to create a script - say foo.py
- in which I want pass from 3 to 6 arguments:
$ python foo.py arg1 arg2 arg3
The first 3 arguments must be given in any case; the last 3 arguments are used in a function that have default argument values if nothing is passed.
The question is how do I do this? So far I was thinking to write something like the following foo.py
(this is an easy example set only for the purpose of having something concrete in support of my question):
import sys
def example(credit_mom, credit_dad, debt_mom, debt_dad = 1000,
salary = 2000, bonus = 0):
total_gain = salary + credit_dad + credit_mom + bonus
total_loss = debt_dad + debt_mom
return total_gain - total_loss
if __name__ == '__main__':
if len(sys.argv) < 4:
sys.exit('Need at least 3 arguments. The order is as follows:\n\
1.credit_mom;\n\
2.credit_dad;\n\
3.debt_mom;\n\
4.others')
else:
sys.exit(example(sys.argv[1],
sys.argv[2],
sys.argv[3],
sys.argv[4],
sys.argv[5],
sys.argv[6]))
If I run this script I clearly get an IndexError
exception:
$ python foo.py 110 110 220
Traceback (most recent call last):
File "foo.py", line 19, in <module>
sys.argv[4],
IndexError: list index out of range