Category Archives

28 Articles

Python局部变量的坑

0   10240 转为繁体

最近碰到这么个问题,有这么个函数,用来将HTML转义字符变回原来的字符:

其中unichr用来将一个整数转换成Unicode字符,仅在Python2中存在。Python3中,chr可以同时处理ASCII字符和Unicode字符。所以我们在Python3环境中将unichr映射到chr上。

运行这段代码会在第8行报错:NameError: free variable ‘unichr’ referenced before assignment in enclosing scope。而且只有Python2会报错,Python3不会。

 

首先从问题上看,报错的原因是在闭包replc里unichr没有定义。

但是Python2明明是有unichr这个内置函数的,为啥就变成未定义呢?

Read More

cloudflare-partner-cli: using CNAME on cloudflare

中文版本

This is a CLI program that let you set CNAME to use Cloudflare using the partner program.

Both Python2.x and Python3.x is supported. No extra library is needed.

To use Chinese menu, set environment variable LANG to use UTF-8 (for example, zh_CN.UTF-8).

Usage

  1. Apply for partner program at https://www.cloudflare.com/partners/.
  2. Clone this repository or download script.
  3. Run python ./cloudflare-partner-cli.py.
  4. Enter your host_key. You can get it here.
  5. Enter the account you use to manage domains (your personal account, not partner login account). User key is stored in .cfhost.
  6. Follow the instructions on screen.

Note

  • Value of resolve_to has to be DNS record (for example: google.com) instead of IP address.

cloudflare-partner-cli: 使用CNAME方式接入Cloudflare

0   11368 转为繁体

English Version

使用Cloudflare partner功能用CNAME方式接入cloudflare。

你可以使用Python2.x或者Python3.x。无需安装任何依赖。

如需使用中文菜单,请将环境变量的LANG设置为使用UTF-8 (比如zh_CN.UTF-8)。

使用方法

  1. 申请Cloudflare partner计划 https://www.cloudflare.com/partners/ 。
  2. clone本项目或者直接下载脚本
  3. 运行 python ./cloudflare-partner-cli.py
  4. 输入 host_key。可以从这里获得。
  5. 输入要用来管理域名的账号 (你的个人账号,不是partner账号)。账户信息保存在.cfhost文件中。
  6. 按照屏幕提示操作。

注意

  • 源站地址必须为DNS记录,如google.com,不能填写IP地址。

 

Python float和decimal

2   10255 转为繁体

在Windows上打包Python脚本时遇到一个需求,将浮点数转成字符数组,比如输入1.001,得到[‘1′,’0′,’0′,’1’]

一开始想当然地用了:

version = 2.001

v = list(str(int(version * 1000)))

发现好像哪里不对,得到的v是[‘1’, ‘0’, ‘0’, ‘0’]。想了一想应该是浮点数的精度问题,因为一看version * 1000 = 1000.9999999999999

所以有这么几种解决方法:

v = list(str(int(round(version * 1000))))

或者:

v = list(str(version).replace(“,”, “”) + “000”)[:4]

或者用decimal模块,decimal是固定小数点位数的,用的是十进制乘除法,所以(在设定的位数内)不会产生误差:

from decimal import getcontext, Decimal

getcontext().prec = 4

v = list(str(Decimal(version) * 1000))

需要注意的是decimal会自动转换科学计数法,可以用”%d” % Decimal(d)来得到原始值。

 

Python中热补丁(Hot Patching)的实现和一些问题

2   16161 转为繁体

有时候我们可能需要只修改一部分代码而且要求修改立即生效,或者为了高可用性不允许停止服务程序,这时我们就需要热补丁

在debian,red hat等系统(或者vista之后的windows)的软件更新时,通常使用替换符号链接来达到高可用性。

对Python来说,解释器预先处理了脚本生成字节码,并读入内存;所以之后硬盘上的文件发生了什么变化,就只能想办法命令解释器重新读入新的脚本。实现这个功能的内建命令是reload

Read More