(一) Python中maxint与系统位数(32/64)的关系

最近在学习Python的正则表达式时,需要批量生成一批随机数据。其中涉及到了模块sys、time中的maxint、ctime,代码在运行ctime格式化时间时候一直报错无法运行。
经过对相关的资料的研究,发现maxint值在不同操作系统是不一样的,在64位操作系统下的maxint>2^32,而在32位操作系统maxint=2^32,ctime函数处理的秒数范围为0~2^32。

旧版本代码

#!/usr/bin/env python

from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxint
# 64 bit has a longer maxint
from time import ctime

tlds = ('com', 'edu', 'net', 'org', 'gov')

for i in xrange(randrange(5, 11)):
    dtint = randrange(maxint)     # pick date
    dtstr = ctime(dtint)          # date string
    llen = randrange(4, 8)        # login is shorter 
    login =''.join(choice(lc) for j in range(llen))
    dlen =  randrange(llen,13)    # domain is longer
    dom =''.join(choice(lc) for j in xrange(dlen))
    print '%s::%s@%s.%s::%d-%d-%d' %(dtstr, login,
        dom, choice(tlds), dtint, llen, dlen)

报错提示

[hbu@localhost Python]$ python gendata.py 
Traceback (most recent call last):
  File "gendata.py", line 13, in <module>
    dtstr = ctime(dtint)          # date string
ValueError: unconvertible time

事例代码是由参考书提供的,理论上maxint获取的值没有问题,在ctime格式化会获得到相应的时间值,此处的报错本不应该发生。后来仔细查看ctime格式时间的范围限定在0~2^32。测试脚本位于CentOS7 64位系统,这样得到的maxint值为9223372036854775807,远大于2^32的值。dtint是由表达式 dtint = randrange(maxint)获取的,这样的dtint在很大概率上会得到大于2^32的值,超出了ctime的处理范围,所以就脚本一直在报错。

maxint值验证

>>> m = maxint
>>> m
9223372036854775807
>>> 2**32
4294967296
>>> 2**64
18446744073709551616L

修改后新版代码

#!/usr/bin/env python

from random import randrange, choice
from string import ascii_lowercase as lc
# from sys import maxint
# 64 bit has a longer maxint
from time import ctime

tlds = ('com', 'edu', 'net', 'org', 'gov')

for i in xrange(randrange(5, 11)):
    dtint = randrange(2**32)     # pick date
    dtstr = ctime(dtint)          # date string
    llen = randrange(4, 8)        # login is shorter 
    login =''.join(choice(lc) for j in range(llen))
    dlen =  randrange(llen,13)    # domain is longer
    dom =''.join(choice(lc) for j in xrange(dlen))
    print '%s::%s@%s.%s::%d-%d-%d' %(dtstr, login,
        dom, choice(tlds), dtint, llen, dlen)

修改后的代码很好的照顾了ctime可处理数值的上限,可得到如下结果:

[hbu@localhost Python]$ python gendata.py 
Thu Nov  4 02:38:42 1982::ymwvvf@peyutywmtfy.org::405254322-6-11
Sun May 25 03:55:09 2008::wegvig@wttsvo.org::1211712909-6-6
Thu Oct 19 14:00:00 2073::zgqgcbs@bqfglyza.net::3275672400-7-8
Wed May 14 13:17:13 2003::ykpksq@raisjbw.edu::1052943433-6-7
Thu Jan  1 00:37:41 2015::eifgiu@geypcbbwn.gov::1420101461-6-9
Tue Jul 28 04:59:18 2043::tkjmit@eaqnbmrxzcd.org::2321697558-6-11
Thu Dec 21 17:40:36 2034::stisf@wqwakqaho.net::2050364436-5-9
Sun May 15 11:07:24 1983::ubydsn@gxbkjhftp.gov::421870044-6-9

  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值