2

This is my code:

today = datetime.date.today()

if len(sys.argv) > 1:
    arg_month = sys.argv[1]
    arg_year = sys.argv[2]
    print arg_month
    print arg_year
    lastMonth = datetime.date(day=1, month=arg_month, year=arg_year)
    first = lastMonth + datetime.timedelta(month=1)
    lastMonth = lastMonth.strftime("%Y%m")
    curMonth = first.strftime("%Y%m")   
else:
    first = datetime.date(day=1, month=today.month, year=today.year)
    lastMonth = first - datetime.timedelta(days=1)
    lastMonth = lastMonth.strftime("%Y%m")
    curMonth=(time.strftime("%Y%m"))

This is how I run the code: python lelan.py 01 2015

the output is:

01
2015
Traceback (most recent call last):
  File "lelan.py", line 22, in <module>
    lastMonth = datetime.date(day=1, month=arg_month, year=arg_year)
TypeError: an integer is required

How to fix this? Thank you.

3
  • I think you might need to change the indices you are accessing to 0 and 1 instead of 1 and 2. In python counting in lists begins from 0 (being the first element) and so on. Commented Mar 27, 2015 at 7:52
  • @adarsh, no sys.argv[0] is the <strike>name</strike> relative path of the script. Commented Mar 27, 2015 at 7:54
  • True! Didn't notice that it was sys.argv. You'll just have to cast the variables to be integers. Commented Mar 27, 2015 at 7:55

2 Answers 2

9

It's because arguments from sys.argv are strings. You need to cast them to integers:

arg_month = int(sys.argv[1])
arg_year = int(sys.argv[2])
Sign up to request clarification or add additional context in comments.

Comments

5

All items gotten from command line arguments are strings; the command line doesn't have any type system, and can't distinguish between strings and anything else. So arg_month and arg_year are strings. You need to cast them to an int explicitly:

int(arg_month)

You may want to consider using the ArgumentParser instead, which can simplify this for you:

parser = ArgumentParser()
parser.add_argument('month', type=int)
...
args = parser.parse_args()
print(args.month)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.