[英]TypeError: an integer is required python
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 这就是我运行代码的方式: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.
谢谢。
It's because arguments from sys.argv
are strings. 这是因为
sys.argv
中的参数是字符串。 You need to cast them to integers: 你需要将它们转换为整数:
arg_month = int(sys.argv[1])
arg_year = int(sys.argv[2])
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. 所以
arg_month
和arg_year
是字符串。 You need to cast them to an int
explicitly: 您需要明确地将它们转换为
int
:
int(arg_month)
You may want to consider using the ArgumentParser instead, which can simplify this for you: 您可能需要考虑使用ArgumentParser ,这可以为您简化:
parser = ArgumentParser()
parser.add_argument('month', type=int)
...
args = parser.parse_args()
print(args.month)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.