Author Archives: felix

sda must have a gpt disk label

安装RHEL时遇到sda must have a gpt disk label的错误,解决方法参考了:http://kms.lenovots.com/kb/article.php?id=13136
I got error ‘sda must have a gpt disk label’ when I was installing RHEL 6.5 64bit. I got solution from the URL above

1.按ctrl+alt+F2进入命令行
I. Press ‘CTRL+ALT+F2’ to get into cml

2.输入parted /dev/sda,进入parted状态,
II. Use ‘parted’ to enter ‘parted’, chose your disk

3.输入mklabel gpt,提示所有数据将被删除,输入yes  //原博客这里写成了pgt,应该是gpt
III. Use ‘mklabel gpt’ to force the disk use gpt, answer yes when the prompt of erasing all data (Caution!!! Be sure you want to erase all data on the disk)

4.按ctrl+alt+F6回到图形界面,点“Back”,再点“Next”重新进入分区界面进行分区。
IV. Press ‘CTRL+ALT+F6’ to go back to installation UI

python随机密码生成/password generator – 试试代码高亮

import string
import random

def pwdgen(size = 8):
    if size < 6:
        return 'Length must be at least 6'
    lchars = string.ascii_lowercase
    uchars = string.ascii_uppercase
    digits = string.digits

    schars = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
#    schars = ''
#    for i in range(33,48):
#        schars += chr(i)
#    for i in range(58,65):
#        schars += chr(i)
#    for i in range(91,97):
#        schars += chr(i)
#    for i in range(123,127):
#        schars += chr(i)

    allchars = schars + lchars + uchars + digits

    pwd = []
    pwd.extend([random.choice(schars) for i in range(random.randint(1,2))])
    pwd.extend([random.choice(lchars) for i in range(random.randint(1,2))])
    pwd.extend([random.choice(uchars) for i in range(random.randint(1,2))])
    pwd.extend([random.choice(digits) for i in range(random.randint(1,2))])
    csize = len(pwd)
    pwd.extend([random.choice(allchars) for i in range(size - csize)])

    random.shuffle(pwd)
    return "".join(pwd)

if __name__ == '__main__':
    size = 8
    print pwdgen(size)

#print newpwd

openstack manual installation troubleshootings

1. [root@controller ~]# nova network-create vmnet –fixed-range-v4=10.0.0.0/24 –bridge-interface=br100 –multi-host=T
ERROR: The server has either erred or is incapable of performing the requested operation. (HTTP 500) (Request-ID: req-bb23e78d-5c1e-4c20-a1c4-c789877604c0)

My reason: compute note cannot reach the mysql of controller node….

2. libvirtError: internal error no supported architecture for os type ‘hvm’
Reason: I’m installing openstack on a vm
Solution: set libvirt_type=qemu in /etc/nova/nova.conf

3. dashboard login failure
[error] DeprecationWarning: Translations in the project directory aren’t supported anymore. Use the LOCALE_PATHS setting instead.DeprecationWarning: Authentication backends without a `supports_inactive_user` attribute are deprecated. Please define it in <class ‘openstack_auth.backend.KeystoneBackend’>.DeprecationWarning: BaseException.message has been deprecated as of Python 2.6Login failed for user “admin”.
Solution: edit /etc/openstack-dashboard/local_settings to set:
OPENSTACK_KEYSTONE_DEFAULT_ROLE = “admin”

Another possible reason: disable selinux please…

Solaris tips(I)

  • stop cacao process

root@felix1 [/] # cacaoadm stop

  • stop desktop process

root@felix1 [/] # svcs -a | grep graphical
online         Sep_18   svc:/application/graphical-login/cde-login:default
root@felix1 [/] # svcadm disable cde-login
root@felix1 [/] # svcs -a | grep graphical
disabled       18:08:37 svc:/application/graphical-login/cde-login:default

  • check the WWN

fcinfo hba-port | grep WWN

  • swupna.jar process

edit /usr/dt/config/Xsession.d/1001.swupnot to comment out the line and kill the process

  • force send mails in queue

/usr/lib/sendmail -q -v

  • route -p xxx writes to /etc/inet/static_route
  • privilege to capture packet on bge

chmod 666 /dev/bge

  • enable mpxio in Solaris 10 for 3par 7200

add configuration to /kernel/drv/scsi_vhci.conf

——
 device-type-scsi-options-list =
“3PARdata”, “symmetric-option”;

symmetric-option = 0x1000000;

——
use /usr/sbin/stmsboot -e to enable multi-pathing
  • checksum and md5
–MD5

digest -v -a md5 a.tar

–checksum
cksum a.tar
–SHA1
digest -v -a sha1 a.tar
  • show mac address by ilom

show /SYS/MB/NET0

  • dbm map “Alias0”: missing map file /etc/mail/aliases

under /etc/mail,

# makemap hash aliases.db < /etc/mail/aliases
  • Solaris 10 language package installation
1 prepare language packages.
All language packages locate in /mountpath/Solaris_10/Product/ of Solaris DVD.
You can either mount an OS iso or nfs source from other servers.
2 list languages which have been installed already
# locale –a
C
POSIX
iso_8859_1
3 install language packages
# localeadm –a korean  -d /cdrom/cdrom0/Solaris_10/Product install Korean
# localeadm –a zh_CN –d /cdrom/cdrom0/Solaris_10/Product install simplified Chinese
Log file is /var/sadm/install/logs/localeadmin_install.2014-01-28
locale/region name is zh_cn
Warning! You have chosen the zh_CN locale rather than a region to install.
This locale is part of the Simplified Chinese region. If you choose to continue, all of the locales in this region will be installed.
Do you wish to continue? [y/n]: y
Adding packages for Simplified Chinese (china)
Region china will be installed.
It takes a few minutes to finish the installation.
4 list languages installed on server
bash-3.2# locale -a
C
POSIX
iso_8859_1
zh
zh.GBK
zh.UTF-8
zh_CN.EUC

用arcconf在线创建StorageTek Raid Controller镜像/Make live mirror with arcconf for StorageTek RAID Controller

X4170 with StorageTek raid controller, 做系统的时候为了节省成本没有做镜像,以至于后来硬盘问题频发导致多次系统crash。让我想到必须做镜像和raid了。研究了下StorMan的手册,发现可以用GUI的StorMan来配置,也可以用arcconf来配置,我没有图形界面,所以只好用arcconf了。

X4170 with StorageTek raid controller has no mirror due to the budget limitation and this caused the OS crash many times by disk failure. This forces me to make mirror for OS. According to the manual of StorMan, this can be done by GUI or arcconf. I have no GUI so I must use arcconf.

其实很简单,至少有一个free的盘,我假设我现有OS的盘是0,0,free的盘是0,1,在线创建的命令为:
It’s easy. At least you need to have a free disk. I assume my OS disk is 0,0 and free disk is 0,1. The live creation command should be:

bash-3.2# arcconf modify 1 from 0 to max 1 0 0 0 1
Controllers found: 1
The requested modification does not support change of logical device size.
The target logical device must be 285696 MB

//I would like to use max as the volume size but the command says the size must be 285696

Command aborted.

bash-3.2# arcconf modify 1 from 0 to 285696 1 0 0 0 1
Controllers found: 1
Reconfiguration of a logical device is a long process. Are you sure you want to continue?
Press y, then ENTER to continue or press ENTER to abort: y

Reconfiguring logical device: os

Command completed successfully.

//It says the process is long but actually it takes less than 1 second.

当然,如果你使用的是新disk,需要首先initialize, 否则会出错://If you’re using a new inserted disk, please initialize first. Otherwise you’ll get aborted

bash-3.2# arcconf modify 1 from 0 to 285696 1 0 0 0 1
Controllers found: 1
Not enough available space.
Not enough available space.

Command aborted.

bash-3.2# arcconf task start 1 device 0 1 initialize
Controllers found: 1
Initializing Channel 0, Device 1.

Command completed successfully.

bash-3.2# arcconf getconfig 1
———————————————————————-

Logical device information
———————————————————————-
Logical device number 0
Logical device name : os
RAID level : 1
Status of logical device : Impacted
Size : 285686 MB
Read-cache mode : Enabled
Write-cache mode : Enabled (write-back)
Write-cache setting : Enabled (write-back) when protected by battery
Partitioned : Yes
Protected by Hot-Spare : No
Bootable : Yes
Failed stripes : No
——————————————————–
Logical device segment information
——————————————————–
Segment 0 : Present (0,0) 00084970458V 3SE0458V
Segment 1 : Present (0,1) 00095371FBS8 3SE1FBS8

命令格式/Command format:

arcconf modify <controller> from <logical_volume> to <volume_size> <raid_level> <disk1 IDs> <disk2 IDs>

Or for a more verbose explanation:

arcconf (the raid utility)

modify (modify an existing raid)

1 (the controller with your simple_volume you want to turn into a raid 1)

from 0 (the logical volume you want to convert into a raid 1)

to 139900 (the size of the volume. In my version of arcconf, this had to be set to a numeric value matching the current simple_volume size, and MAX was not a valid option)

1 (the raid level you want to convert to)

0 0 (the first disk ID (0,0) in the raid 1. This should be your existing disk containing the simple_volume that you want to convert to raid 1)

0 1 (the extra available disk ID (0,1) that you are adding to the raid 1 to make it a mirror)

Python核心编程第二版 学习笔记


10/6/13 第四章


  • 步进切片
>>> a=’iloveyoubaby’
>>> a[::-1]
‘ybabuoyevoli’
>>> a[::-2]

‘yauyvl’

应用场景:字符串反转
  • 不同变量指向同一个变量(这点很奇怪)

>>> a
[1, 2, 3, 4]
>>> b=a
>>> a is b
True
>>> a.append(5)
>>> a is b
True
>>> b
[1, 2, 3, 4, 5]
>>> b is a
True

>>> a=3
>>> b=a
>>> a*=3
>>> b
3
>>> a
9
>>> b is a
False
  • 内置比较函数cmp

cmp(a,b), a==b, 则0,a<b, -1, a>b, 1

用户自定义对象使用cmp,会调用类的特殊方法__cmp__
  • repr() == “, 但“不鼓励使用
  • isinstance的用法和type(x).__name__
>>> b=(2,3,4)

>>> isinstance(b, (tuple))
True
>>> isinstance(5, (int))
True

>>> print type(b).__name__
tuple
  • scalar 标量
  • python的int相当于c的长整型,fload相当于c的double
  • type(a)==type(b)是值的比较,type(a) is type(b)是身份的比较,后者更为高效

10/6/13 第五章 数字


  • 八进制以0开头,十六进制以0x或0X开头
  • long int 只和虚拟内存大小有关,所以能表示很大
  • python除法一般都是地板除
  • 位运算:取反~,按位与&,或|,异或^,左移<<,右移>>
  • coerce这个函数好奇怪
  • divmod
  • pow可以接受第三个参数,居然是前两个进行指数运算然后对第三个进行取余,真神经啊
  • round第二个参数可以指定四舍五入的位数
  • 进制转换函数ord和chr
  • 没有__nonzero__()方法的对象默认值都是false

10/6/13 第六章 sequence, string, list and tuple


  • + 操作符对于连接操作未必是最有效的
  • None也可以作为index,如:
>>> i=’iloveyouqingqing’
>>> i[:None]
‘iloveyouqingqing’
     [None].extend(…的返回值是None,所以
  • 单引号和双引号的作用是相同的
  • 字符串的正向索引以0开头,反向索引以-1开始(从最末尾)
  • 切片时,a[5:7]仅为a[5]和a[6],不包括a[7]
  • string预定义的字符串:

string.ascii_uppercase
string.ascii_lowercase
string.ascii_letters
string.digits

  • string.upper()可以转换大写
  • for-else结构,else是for执行过程中没有遇到break,再执行的部分
  • python为每个新字符串分配新内存,为性能计,建议用join连接字符串

>>> ‘ ‘.join((‘aa’, ‘bb’, ‘cc’))
‘aa bb cc’
>>> ‘;’.join((‘aa’, ‘bb’, ‘cc’))
‘aa;bb;cc’

  • unicode的字符串前面带u,和普通字符串连接时自动转换

>>> ‘Hello’ + u’ ‘ + ‘World’ + u’!’
u’Hello World!’

  • print可以用tuple方式,也可以用dict方式
  • string 的 substitute用法

>>> from string import Template
>>> s = Template(‘here is ${num} ${name}’)
>>> s.substitute(num=3, name=’babies’)
‘here is 3 babies’

  • 原始字符串用r’ a string’可以过滤特殊符号
  • string自带函数

enumerate()
>>> a
‘iloveyou’
>>> for i,t in enumerate(a):
print i,t

0 i
1 l
2 o
3 v
4 e
5 y
6 o
7 u

cmp()
zip()
>>> s, t = ‘abc’, ‘xyzefg’
>>> zip(s, t)
[(‘a’, ‘x’), (‘b’, ‘y’), (‘c’, ‘z’)]
>>> unicode(‘abc’)
u’abc’
>>> isinstance(‘abc’, str)
True
>>> isinstance(u’abc’, unicode)
True
>>> chr(65)
‘A’
>>> ord(‘a’)
97
>>> a.center(100)
‘                                              iloveyou                                              ‘
>>> a.count(‘o’)
2
>>> a.title()
‘Iloveyou’
>>> a.split(‘o’)
[‘il’, ‘vey’, ‘u’]
>>> a.index(‘o’)
2
>>> a.find(‘o’)
2 // index如果sub str 不存在时会出exception,find则返回-1
>>> a.center(100).strip()
‘iloveyou’
>>> a.center(100).lstrip()
‘iloveyou                                              ‘
>>> a.center(100).rstrip()
‘                                              iloveyou’
>>> a.zfill(50)
‘000000000000000000000000000000000000000000iloveyou’
>>> a.replace(‘o’, ‘bbb’)
‘ilbbbveybbbu’
>>> a.startswith(‘ilove’)
True
>>> a.endswith(‘you’)
True
  • ”’三引号可以包含换行,制表,特殊符号
  • 字符串是不可变对象,a[2] = ‘b’ 之类会fail
  • 看起来python的file的write和read都直接支持了unicode(包括utf8)的写入
  • 列表可以更改,也可以包含用户自定义对象
  • 一些列表内建函数

>>> a=[‘i’, ‘love’, ‘you’, ‘very’, ‘much’]
>>> reversed(a)
<listreverseiterator object at 0x0297A5D0>    //这个返回值居然不是list
>>> for t in reversed(a):
print t

much
very
you
love
i
>>> sorted(a)
[‘i’, ‘love’, ‘much’, ‘very’, ‘you’]

enumerate() 类似string
>>> for i, t in enumerate(a):
print i, t

0 i
1 love
2 you
3 very
4 much

sum(a),求和
list.append(obj)
list.insert(index, obj)
list.pop(index = -1) //看起来还可以用不同的index,应该和remove差不多,不过这个倒是有返回值
list.index()不用于检查list是否存在某个元素,先用in/not in
list.reverse() extend,sort和reverse都没有返回值
>>> a.sort()
>>> a
[‘i’, ‘love’, ‘much’, ‘very’, ‘you’]
>>> a.reverse()
>>> a
[‘you’, ‘very’, ‘much’, ‘love’, ‘i’]
>>> b = [‘here’, ‘is’, ‘not’, ‘my’, ‘hometown’]
>>> a.extend(b)
>>> a
[‘you’, ‘very’, ‘much’, ‘love’, ‘i’, ‘here’, ‘is’, ‘not’, ‘my’, ‘hometown’]
  • 用for构造list

>>> [x for x in b]
[‘here’, ‘is’, ‘not’, ‘my’]

  • list可用于构造其他数据类型,如stack 或者queue
  • 看到一个很有趣的函数调用方法,使用了字典,python还真是方便啊

CMDs = {‘u’: pushit, ‘o’: popit, ‘v’: viewstack}

CMDs[choice]()
  • 使用ctrl+d或者ctrl+c退出

try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice = ‘q’

  • tuple是不可变对象
  • tuple是逗号分隔的多对象的默认集合类型,函数返回的多对象也是tuple

return obj1, obj2, obj3

  • 由于()被重载,定义单元素tuple必须在元素后加逗号,例如(‘xyz’,)
  • 传递tuple给函数可以防止变量被修改,list()和tuple()可互相转换
  • [:],list()/tuple(),copy模块的copy函数均可用于浅拷贝,浅拷贝时,内容并未改变
  • copy.deepcopy()用于深拷贝
  • tuple只能浅拷贝

10/11 第七章 映射和集合

  • 字典创建可以用{},可以用dict()和fromkeys()

>>> a = { ‘x’: 15, ‘y’: 88 }
>>> a
{‘y’: 88, ‘x’: 15}
>>> a[‘y’]
88
>>> b = dict(([‘x’, 1], [‘y’, 2]))
>>> b
{‘y’: 2, ‘x’: 1}
>>> c = {}.fromkeys((‘x’, ‘y’), 3)
>>> c
{‘y’: 3, ‘x’: 3}

>>> dict(x=1, y=2)
{‘y’: 2, ‘x’: 1}
>>> d = a.copy()   //效率更高
>>> d
{‘y’: 88, ‘x’: 15}
  • 访问字典

>>> for key in a.keys():
print key, a[key]

y 88
x 15

  • key是不允许改变的,可以判断key是否存在
>>> ‘x’ in a
True
>>> a.has_key(‘x’)
True
  • 字典的输出
>>> print ‘key x value is %(x)s, key y value is %(y)s’ %a
key x value is 15, key y value is 88
  • 字典删除

del dict2[‘name’] # 删除键为“name”的条目
dict2.clear() # 删除dict2 中所有的条目
del dict2 # 删除整个dict2 字典
dict2.pop(‘name’) # 删除并返回键为“name”的条目

  • 常用函数

dict.get(key, default=None),如果key不存在会返回默认值,默认值是None

sorted(dict)返回的是key的list
  • 集合,看起来有唯一性
  • 常用操作

in , not in

for x in s: …
add
update,//添加了
remove
-=
>, >=和<, <=表示的是子集
| 联合, |=
& 交集, &=
– 差集, -=

10/12 条件和循环


  • 一个简单的语句:

>>> a=3;b=4;c=a if a < b else b;c
3

  • range函数

range(start, end, step =1)

  • for也支持for(i=0; i < 10; i += 1)这样的语法
  • xrange()不会在内存里生成列表,所以效率更高
  • pass不做任何事
  • 使用iter()创建迭代器

>>> a=(1,3,9,3,5,9)
>>> b=iter(a)
>>> b.next()
1
>>> b.next()
3

  • 迭代器的next()的exception是StopIteration
>>> while True:
try:
b.next()
except StopIteration:
break
  • 在迭代时对内容进行操作不合适
  • 列表解析(list comprehensions)语法:

[expr for iter_var in iterable]

扩展语法:
[expr for iter_var in iterable if cond_expr]
更复杂的:
>>> [ (x, y) for x in range(3) for y in range(5) ]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]
读文件:
>>> f = open(‘a.txt’, ‘r’)
>>> [ word for line in f for word in line.split() ]
  • 列表解析会一次生成所有数据,大数据量下回造成内存过大,此时应使用生成器表达式

(expr for iter_var in iterable if cond_expr)

>>> for a in (word for line in f for word in line.split()): //看起来生成器表达式出来的是个不可打印对象
print a

hello
dear

下面这个生成器表达式太简洁了:
return max(len(x.strip()) for x in open(‘/etc/motd’))

10/12 第九章 文件输入输出


  • b模式在unix/linux下没什么用
  • 基本语法 file_object = open(file_name, access_mode=’r’, buffering=-1)
  • U是通用换行符,支持跨平台
  • read读取字节到字符串
  • readline返回一行
  • readlines默认读取剩下所有行,也可以指定字节数
  • xreadlines是逐行读取,更高效,不过已经被iter(file)替代,甚至可以用for eachLine in f…代替
  • read or readlines时,并不会删除结束符,需要自己处理

[line.strip() for line in f.readlines()]

  • seek格式

seek(offset[, whence]) -> None

可选的whence有3个可选值,0从头,1从当前位置,2从文件尾
  • 一些函数 fileno(), flush(), isatty() //有啥用?, truncate()
  • 跨平台:os的五个属性
linesep 用于在文件中分隔行的字符串
sep 用来分隔文件路径名的字符串
pathsep 用于分隔文件路径的字符串
curdir 当前工作目录的字符串名称
pardir (当前工作目录的)父目录字符串名称
  • tell()可以报告当前字节位置
  • argv的分析简单用getopt,复杂用optparse
  • os模块

remove()/unlink() Delete file 删除文件
rename()/renames()b 重命名文件
symlink() 创建符号链接
utime() 更新时间戳
tmpfile() 创建并打开(‘w+b’)一个新的临时文件
walk()a 生成一个目录树下的所有文件名
目录/文件夹
chdir()/fchdir()a 改变当前工作目录/通过一个文件描述符改变当前工作目录
chroot()d 改变当前进程的根目录
listdir() 列出指定目录的文件
getcwd()/getcwdu()a 返回当前工作目录/功能相同, 但返回一个 Unicode 对象
mkdir()/makedirs() 创建目录/创建多层目录
rmdir()/removedirs() 删除目录/删除多层目录
访问/权限
access() 检验权限模式
chmod() 改变权限模式
chown()/lchown()a 改变 owner 和 group ID/功能相同, 但不会跟踪链接
umask() 设置默认权限模式

basename() 去掉目录路径, 返回文件名
dirname() 去掉文件名, 返回目录路径
join() 将分离的各部分组合成一个路径名
split() 返回 (dirname(), basename()) 元组
splitdrive() 返回 (drivename, pathname) 元组
splitext() 返回 (filename, extension) 元组
信息
getatime() 返回最近访问时间
getctime() 返回文件创建时间
getmtime() 返回最近文件修改时间
getsize() 返回文件大小(以字节为单位)
exists() 指定路径(文件或目录)是否存在
isabs() 指定路径是否为绝对路径
isdir() 指定路径是否存在且为一个目录
isfile() 指定路径是否存在且为一个文件
islink() 指定路径是否存在且为一个符号链接
ismount() 指定路径是否存在且为一个挂载点
samefile() 两个路径名是否指向同个文件

  • pickle, marshal, shelve, cPickle 提供python对象永久存储

10/13 错误和异常


  • 可以使用多个except为每个exception定义语句
  • KeyboardInterrupt 和 SystemExit和Exception平级,所以想要catch所有exception,需要使用BaseException (top exception)
  • except Exception, reason中,reason是一个类实例
  • try没有catch到exception的时候会转向else
  • finally可用于catch多个exception
  • try-finally
  • 在2.6才有的with语句,只有少数模块支持
with open(‘/etc/passwd’, ‘r’) as f:
for eachLine in f:
# …do stuff with eachLine or f…
  • raise语句用于触发异常
  • assert用于断言语句,True则不产生任何动作否则触发AssertionError,如果不catch就退出程序提供trackback

>>> assert 1 == 0

Traceback (most recent call last):
File “<pyshell#289>”, line 1, in <module>
assert 1 == 0
AssertionError
>>> assert 1 == 0, ‘What the hack!’

Traceback (most recent call last):
File “<pyshell#290>”, line 1, in <module>
assert 1 == 0, ‘What the hack!’
AssertionError: What the hack!

  • assert的AssertionError可以用try来catch
  • 创建一个异常很简单,不过我还没有读10.9的创建异常的例子

>>> class NetworkError(IOError):
pass

  • 联系依然没做

10/14 十一章 函数


  • python支持不用显式的传入的参数,即将参数放入tuple或dict
  • 一个random的randint的例子

from random import randint
[randint(1,10) for i in range(2)]

  • random还有choice这么一个函数

>>> from random import choice
>>> choice(‘-+’)
‘+’

  • 居然用变量调用函数
ops = {‘+’: add, ‘-‘: sub}
ans = ops[op](*nums)
  • 函数也有属性,例如__doc__
  • 内部函数,可以在一个函数内定义另一个函数,无耻
  • 装饰器
class MyClass(object):
@staticmethod
def staticFoo():
==staticmethod(staticFoo())
  • 一个变量可以等于一个函数

def foo():

  pass
bar = foo
  • 函数还可以当做参数传入函数
  • 默认参数不能在非默认参数之前
  • 用*号指定可变参数元祖(非关键字参数)

def tupleVarArgs(arg1, arg2=’defaultB’, *theRest):

  • 用**号指定可变参数字典(关键字参数)
  • 关键字参数和非关键字参数的区别是,关键字参数需要指定关键字名称
例如:
def newfoo(arg1, arg2, *nkw, **kw)

newfoo(10, 20, 30, 40, foo=50, bar=60)

另外的调用方式:newfoo(2, 4, *(6, 8), **{‘foo’: 10, ‘bar’: 12})

  • lambda用于创建匿名函数

>>> a = lambda x, y=2: x + y
>>> a(100)
102

  • filter(func, seq),用seq里的元素依次调用func(返回值为bool),返回一个值为true的值的序列

>>> def odd(x):
return x % 2

>>> filter(odd, (1, 3, 8, 19))
(1, 3, 19)

>>> filter(lambda n: n % 2, (1, 3, 4, 9, 12))
(1, 3, 9)
  • map(func, seq)返回的是结果值的列表

>>> map(lambda n: n%2, (1, 3, 4))
[1, 1, 0]

>>> map(lambda x, y: (x+y, x-y), [1,3,5], [2,4,6])
[(3, -1), (7, -1), (11, -1)]
//带多个序列作为参数对

  • partial偏函数,先固定指定一个参数
>>> from functools import partial
>>> baseTwo = partial(int, base=2)
>>> baseTwo(‘100010’)
34
  • Closures: 闭包函数?

>>> def counter(start_at = 0):
count = [ start_at ]
def incr():
count[0] += 1
return count[0]
return incr

>>> count = counter(5)
>>> count()
6
>>> count()
7

  • 生成器:协同程序,可以暂停或者挂起,下次调用时,从挂起处继续执行,迭代器也是生成器,用next()调用,没有更多值时抛出StopIteration异常,可以用for来执行

>>> def gen():
yield 1
yield 2

>>> g = gen()
>>> g.next()
1
>>> g.next()
2

>>> for i in gen():
print i

1
2

新特性是用send发送值和用close()结束迭代

10/17 第十二章 模块


  • sys.path是搜索路径
  • 可以在任意位置为函数或对象添加属性

>>> def foo():
pass

>>> foo.a = 100

//这不丧心病狂么?
  • import建议顺序:标准库,第三方,自定义,中间用空行分隔
  • import…as语句:import Tkinter as tk
  • 可以从zip文件导入module(py,pyc,pyo)
  • __import__函数用于自定义导入算法
  • reload(module)用于重新导入module,如reload(sys)
  • 包的结构例子:
Phone/
     __init__.py
     common_util.py
     Voicedta/
          __init__.py
          Pots.py
          Isdn.py
          Fax/
               __init__.py
               G3.py
          Mobile/
其中__init__.py是导入初始化文件,可以为空
包的导入例子:
import Phone.Mobile.Analog
Phone.Mobile.Analog.dial()
from Phone import Mobile
Mobile.Analog.dial(‘555-1212’)
from Phone.Mobile import Analog
Analog.dial(‘555-1212’)
from Phone.Mobile.Analog import dial
dial(‘555-1212’)
  • 使用 from module import *时,应在__init__.py中加入__all__字符串列表,包含所有需要导入的模块名字
  • 相对导入是如何导入的呢?
  • 给不想被导入的变量前加一个_即可防止被导入,但不能防止绝对导入
  • 指定不同的编码的源文件,例如utf8:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
  • 循环导入可能导致都不能导入

10/18 Chapter 13: OOP


  • 创建类

class MyNewObjectType(bases): //新式类,必须继承一个父类,可以使用object作为基类

class MyNewObjectType: //经典类,md这有啥区别
  • self参数是自动传入方法的,所以不需要显式传入
  • __init__()类似于类构造器
  • 奇怪的使用父类的__init__()的方法(没有parent关键字)
class EmplAddrBookEntry(AddrBookEntry):
‘Employee Address Book Entry class’#员工地址本类
     def __init__(self, nm, ph, id, em):
          AddrBookEntry.__init__(self, nm, ph)
          self.empid = id
          self.email = em
  • 类名通常由大写字母打头
  • 方法必须要绑定到实例才能运行
  • 类的特殊属性
C.__name__ 类C的名字(字符串)
C.__doc__ 类C的文档字符串
C.__bases__ 类C的所有父类构成的元组
C.__dict__ 类C的属性
C.__module__ 类C定义所在的模块(1.5 版本新增)
C.__class__ 实例C对应的类(仅新式类中)
  • __new__() 构造器
  • __del__()解构器

先调用父类__del__()

del x不代表执行x的__del__,仅减少引用计数
__del__()未捕获的异常会被忽略掉
  • __init__() should return None
  • instance has two special properties: __class__ and __dict__
  • 可以访问类属性,类属性改变时,实例属性会随之改变,如果实例属性制定了新值,将会首先访问到实例属性,可以del掉实例属性,然后又可以访问到类属性
  • staticmethod()和classmethod(),目前还没看出来有啥区别
  • 可以使用super()函数来调用基类函数,也可以直接指定基类名字调用
class C(P):
     def foo(self):
          super(C, self).foo()
          print ‘Hi, I am C-foo()’
  • 字符串的ljust()函数

>>> ‘dkd’.ljust(12)
‘dkd         ‘

  • 多重继承时,经典类深度优先,新式类广度优先,从左至右搜索名字
  • 内置函数

issubclass()

isinstance()
hasattr(), getattr(), setattr(), delattr()
vars()
  • 定制类的关键点:

C.__str__(self) 可打印的字符输出;内建str()及print 语句

__add__() 重载 + 号
__iadd__() 重载 +=
__repr__ = __str__ 可以直接复制函数
__iter__创建迭代器,只返回self
  • 双下划线的方法在运行时是不允许被直接访问的,相当于private
  • 授权

– 覆盖__getattr__()可以实现授权,用getattr()获得属性

  • 三类时间ctime, mtime and atime
  • isinstance() 不如 is 严谨
  • 使用__slot__代替__dict__用于属性少但实例多的对象,可以大量节省内存
  • property(fget=None, fset=None, fdel=None, doc=None) 用于设定类的属性获取,设置等等函数
  • __metaclass__貌似是在规定一个子类必须做的事情

10/20 Chapter 14, 执行环境


  • eval执行表达式,exec执行可执行语句
  • exec也可以执行文件对象
  • raw_input的结果永远是字符串,input输入的结果是表达式对象
  • 字符串赋值也可用%(var…)的方式

>>> a = “i”
>>> b = “love”
>>> c = ” %s %s u” % (a, b)
>>> c
‘ i love u’

  • 模块导入时,模块最高级的代码就会执行!
  • 如何处理那些不想每次导入都执行的代码呢?缩进它,并放入if __name__ == ‘__main__’ 的内部
  • execfile(filename)等价于:
f = open(filename, ‘r’)
exec f
f.close()
execfile的完整语法是:execfile(filename, globals=globals(), locals=locals())
  • 两个从命令行执行模块的命令

python -c “import CGIHTTPServer; CGIHTTPServer.test()”

python -m CGIHTTPServer
  • 执行非python程序

均为os模块内:

system(cmd)
fork()
execl(file, arg0,arg1,…)
exec*….
wait()
  • os.system(cmd) 执行时,python程序是挂起的,返回值是cmd的退出状态
  • os.popen(cmd) 返回一个文件对象,w可以写入值,r可以读取值
  • fork()和wait()的用法
ret = os.fork() # spawn 2 processes, both return #产生两个进程,都返回
if ret == 0: # child returns with PID of 0 #子进程返回的PID 是0
     child_suite # child code #子进程的代码
else: # parent returns with child’s PID #父进程返回是子进程的PID
     parent_suite # parent code #父进程的代码
ret = os.fork()
if ret == 0: # child code #子进程代码
     execvp(‘xbill’, [‘xbill’])
else: # parent code #父进程代码
     os.wait() # 等待并reaping child,也可以稍后reap
//调用wait()父进程会挂起直到子进程完成
  • Popen类用于取代popen()??
  • sys.exit(status=0)调用时,会引发SystemExit异常
  • sys.exitfunc()需要自己改写,本身是不可用的(P616)

def my_exit():

   xxxx
sys.exitfunc = my_exit
  • os.kill()

10/22 Chapter 15: RegEx


  • re.match()从头开始搜索,re.search()搜索任意位置
  • group()是整个字符串,group(N)为括号获取的匹配子串
  • findall()返回的是一个list
  • subn()比sub()多返回一个匹配次数的数字
  • \s匹配任意空白字符
  • 要表示\b,需要使用\\b或者使用raw string
  • ^(Mon|Tue|Wed) == ^Mon|^Tue|^Wed
  • 使用?限制贪婪匹配
>>> s = ‘68372498798324-33434’
>>> m = re.match(‘.+(\d+-\d+)’, s)
>>> m.group(1)
‘4-33434’
>>> m = re.match(‘.+?(\d+-\d+)’, s)
>>> m.group(1)
‘8372498798324-33434’

10/23 Chapter 16, Internet programming


  • socket(socket_family, socket_type, protocol=0)

socket_family 可以是AF_UNIX 或AF_INET。socket_type 可以是SOCK_STREAM 或SOCK_DGRAM。

  • SocketServer模块,高级别socket实现

10/23 Chapter 17, Network client programming


  • ftp模块的retrive使用方式:
f.retrbinary(‘RETR %s’ % FILE, open(FILE, ‘wb’).write)

10/23 Chapter 18, Threading…


  • 不建议使用thread而使用threading模块
  • Queue模块提供多个线程之间共享的数据队列
  • thread模块可以使用lock来进行线程同步

10/23 Chapter 19 GUI programming


  • 跳过

10/24 Chapter 20, Web programming


  • URL部件名称
prot_sch://net_loc/path;params?query#frag
——————————————–
Table 20.1 Web Address Components
URL 部件 描述
prot_sch 网络协议或者下载规划
net_loc 服务器位置(或许也有用户信息)
path 斜杠( / )限定文件或者CGI 应用程序的路径。
Params 可选参数
query 连接符( & )连接键值对
frag 拆分文档中的特殊锚
  • urlparse模块

urlparse.urlparse()返回的是一个(prot_sch, net_loc,path, params, query, frag) 元组

  • urllib模块

urllib.urlopen()返回的是一个文件对象

要使用POST,可以将数据放入urlopen(urlstr, postQueryData=None)的postQueryData中
  • urllib2模块更高级(跳过了)

后面都跳过了


10/23 Chapter 21, database programming


  • 跳过

10/23 Chapter 22, 扩展Python


3PAR 7200 setup and installation

Setup Procedure:

1. Physically cable the 3PAR, connect the mgt ports
2. Have a ESXi server in the same subnet, use Virtual Service Processor’s VOF template to deploy the VSP
3. In the console of VSP, use setupusr with blank password to setup the VSP IP
4. Use the SmartStart to connect to VSP to configure VSP and storage
5. Install management console to connect to storage for management

Change IP address of 7200

1. ssh to 3par 7200 storage with user 3paradm
2. setnet startaddr <old-IP> <new-IP> <new-subnet-mask>
3. setnet startgateway / setnet cleargateway
4. Now the storage listen to both new IP addresses and old address, try to ssh to new IP address to verify your IP
5. shownet will see the new IP verified, use ‘setnet finish’ to finish the configuration

zfs的迁移(zfs migration)

需要做ZFS的迁移用于两台机器之间的互备,所以做了个ZFS迁移的测试,在vmware下创建了新磁盘,测试了分别在两台vm上的导入导出和数据。

1. 创建zpool

zpool create ztest c1t3d0

2. 拷贝数据并export

zpool export ztest

此时挂载被umount

3. 把磁盘添加到另外一台主机,查看可否import

-bash-3.2# zpool import
pool: ztest
id: 3289554358798268199
state: ONLINE
action: The pool can be imported using its name or numeric identifier.
config:

ztest ONLINE
c1t5d0 ONLINE

4. 直接import

-bash-3.2# zpool import ztest
-bash-3.2# df -k
Filesystem kbytes used avail capacity Mounted on
rpool/ROOT/s10zfsdb 30707712 10978054 13975936 44% /

rpool 30707712 42 13975936 1% /rpool
ztest 10257408 31 10257323 1% /ztest

可用于一些不太需要热备的地方把数据迁移至另外一台主机。两台主机需要有相同的patch版本,准确的说,是相同的zfs版本

php with Apache tips

1. If you found sometimes you cannot see any data from server and you see the log below:

[Thu Jul 18 18:08:30 2013] [notice] child pid 24544 exit signal Segmentation fault (11)

That means your apache and php doesn’t work well together, you need to try to make another installation

2. If you find you cannot start apache with php, get alert like this:

httpd: Syntax error on line 53 of /usr/local/apache2/conf/httpd.conf: Cannot load /usr/local/apache2/modules/libphp5.so into server: ld.so.1: httpd: fatal: relocation error: file /usr/local/apache2/modules/libphp5.so: symbol sapi_module: referenced symbol not found

Maybe you can install a lower version of php and apache to fix it.

 

不错的Hiking地点: Castle Rock State Park

类型:State park
适宜:Hiking
特色:不错的hiking地点,植被繁茂,有一些不错的大石头,所以有些攀岩的人,有山景,不过从17开过去的路比较窄
费用:admission free,公园门外可以street parking,公园里也可以parking,不过这里的地图要2块一张

在湾区玩了很多不错的公园,这个公园是比较适宜hiking的,有些不错的trail