Blog

  • python的入门的几个例子(中)

    接着上一个http://jpuyy.com/2012/12/python-simple-programs-a.html

    例11.三引号,while循环–Triple-quoted strings, while loop

    REFRAIN = '''
    %d bottles of beer on the wall,
    %d bottles of beer,
    take one down, pass it around,
    %d bottles of beer on the wall!
    '''
    bottles_of_beer = 99
    while bottles_of_beer > 1:
        print REFRAIN % (bottles_of_beer, bottles_of_beer,
            bottles_of_beer - 1)
        bottles_of_beer -= 1

    例12.python中的类–Classes

    class BankAccount(object):
        def __init__(self, initial_balance=0):
            self.balance = initial_balance
        def deposit(self, amount):
            self.balance += amount
        def withdraw(self, amount):
            self.balance -= amount
        def overdrawn(self):
            return self.balance < 0
    my_account = BankAccount(15)
    my_account.withdraw(5)
    print my_account.balance

    执行结果是10

    例13.使用unittest模块进行单元测试–Unit test with unittest

    import unittest
    def median(pool):
        copy = sorted(pool)
        size = len(copy)
        if size % 2 == 1:
            return copy[(size - 1) / 2]
        else:
            return (copy[size/2 - 1] + copy[size/2]) / 2
    class TestMedian(unittest.TestCase):
        def testMedian(self):
            self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
    if __name__ == '__main__':
        unittest.main()

    执行过程:将中间值计算出来与7比较,如果相等,则通过测试。

    例14.基于Doctest的测试–Doctest-based testing

    def median(pool):
        '''Statistical median to demonstrate doctest.
        >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8])
        7
        '''
        copy = sorted(pool)
        size = len(copy)
        if size % 2 == 1:
            return copy[(size - 1) / 2]
        else:
            return (copy[size/2 - 1] + copy[size/2]) / 2
    if __name__ == '__main__':
        import doctest
        doctest.testmod()

    执行结果:没有输出任何东西,说明中间值是7

    例15.使用itertools模块

    from itertools import groupby
    lines = '''
    This is the
    first paragraph.
    
    This is the second.
    '''.splitlines()
    # Use itertools.groupby and bool to return groups of
    # consecutive lines that either have content or don't.
    for has_chars, frags in groupby(lines, bool):
        if has_chars:
            print ' '.join(frags)
    # PRINTS:
    # This is the first paragraph.
    # This is the second.

    例16.csv模块,元组拆分,内置函数cmp() — csv module, tuple unpacking, cmp() built-in

    import csv
    
    # write stocks data as comma-separated values
    writer = csv.writer(open('stocks.csv', 'wb', buffering=0))
    writer.writerows([
        ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),
        ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22),
        ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)
    ])
    
    # read stocks data, print status messages
    stocks = csv.reader(open('stocks.csv', 'rb'))
    status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
    for ticker, name, price, change, pct in stocks:
        status = status_labels[cmp(float(change), 0.0)]
        print '%s is %s (%s%%)' % (name, status, pct)

    例18. 八皇后问题,递归–8-Queens Problem (recursion)

    BOARD_SIZE = 8
    
    def under_attack(col, queens):
        left = right = col
    
        for r, c in reversed(queens):
            left, right = left - 1, right + 1
    
            if c in (left, col, right):
                return True
        return False
    
    def solve(n):
        if n == 0:
            return [[]]
    
        smaller_solutions = solve(n - 1)
    
        return [solution+[(n,i+1)]
            for i in xrange(BOARD_SIZE)
                for solution in smaller_solutions
                    if not under_attack(i+1, solution)]
    for answer in solve(BOARD_SIZE):
        print answer
  • ubuntu安装jdk7

    第一步:添加JDK7的源

    # Step 1: Add the repository for JDK 7.

    sudo apt-add-repository ppa:webupd8team/java

    第二步:更新

    # Step 2: Update

    sudo apt-get update

    第三步:安装JDK及附加组件

    # Step 3: Install JDK and associated utilities

    sudo apt-get install oracle-java7-installer

    第四步:设置默认编译器

    # Step 4: Set the default java interpreter used by the system.

    sudo update-alternatives --config java
  • python获取日期和时间的方法

    使用datetime模块

    #!/usr/bin/env python 
    #-*- coding:utf-8 -*- 
    #author: jpuyy date jpuyy.com
    
    import datetime
    
    now = datetime.datetime.now()
    
    print
    print "以str显示datetime对象"
    print str(now)
    
    print "使用实例属性"
    print "今年是%d年" % now.year
    print "现在是%d月" % now.month
    print "今天是%d号" % now.day
    print "现在%d点了" % now.hour
    print "现在是%d分" % now.minute
    print "当前是%d秒" % now.second
    print "当前微秒值是%d, 1秒=1000000微秒" % now.microsecond
    
    print "用strftime()显示格式化的时间"
    print now.strftime("%Y-%m-%d %H:%M:%S")

    执行结果

    以str显示datetime对象
    2013-01-29 16:53:12.895591
    使用实例属性
    今年是2013年
    现在是1月
    今天是29号
    现在16点了
    现在是53分
    当前是12秒
    当前微秒值是895591, 1秒=1000000微秒
    用strftime()显示格式化的时间
    2013-01-29 16:53:12
  • update-rc.d的用法

    update-rc.d为debian/ubuntu管理开机启动的工具,类似于chkconfig

    详细用法可查阅帮助信息

    update-rc.d --help

    查看系统当前的初始化服务

    $ ls /etc/init.d/
    $ ls /etc/rc?.d

    增加或删除开机启动项

    update-rc.d -f <service> remove # 删除开机启动项服务
    update-rc.d <service> start <order> <runlevels> # 新增系统启动项服务
    update-rc.d <service> stop <order> <runlevels> # 停用某系统启动项

    修改启动项的启动级别

    update-rc.d [-n] name disable|enable [ S|2|3|4|5 ]

    例子

    update-rc.d php-fpm defaults # 新增系统启动项,开机即运行php-fpm服务
    update-rc.d -f apache2 remove # 将apache2从启动项里删除
    update-rc.d minecraft_server defaults #开机运行minecraft
    update-rc.d -f minecraft_server remove #将minecraft从启动项移除

    如将pptpd从开机启动中移除

    # update-rc.d -n -f pptpd remove
     Removing any system startup links for /etc/init.d/pptpd ...
     /etc/rc1.d/K20pptpd
     /etc/rc2.d/S20pptpd
     /etc/rc3.d/S20pptpd
     /etc/rc4.d/S20pptpd
     /etc/rc5.d/S20pptpd

    自己编译安装的想要加到开机运行服务中,还可以编写一个abc文件,具体可参考其他/etc/init.d/中的文件,放到/etc/init.d/abc

    #! /bin/sh
    # /etc/init.d/abc
    #
    # Some things that run always
    touch /var/lock/abc
    # Carry out specific functions when asked to by the system
    case "$1" in
     start)
     echo "Starting script abc "
     echo "Could do more here"
     ;;
     stop)
     echo "Stopping script abc"
     echo "Could do more here"
     ;;
     *)
     echo "Usage: /etc/init.d/abc {start|stop}"
     exit 1
     ;;
    esac
    exit 0

    给其加上权限

    chmod 755 /etc/init.d/abc

    添加启动链接即可

    # update-rc.d abc defaults
  • 常见的ipv6地址或前缀

    ::/128 0:0:0:0:0:0:0:0
    未指定地址。只能作为尚未获得正式地址的主机的源地址,不能作为目的地址,不能分配给真实的网络接口
    ::1/128 0:0:0:0:0:0:0:1
    回环地址,相当于ipv4中的localhost(127.0.0.1),在windows下,ping locahost可得到此地址

    2001::/16 全球可聚合地址,由 IANA 按地域和ISP进行分配,是最常用的IPv6地址。2001::/32- 用于Teredo tunneling。如

    ping6 cgbt.cn(2001:da8:205::100)

    ping6 ipv6.cczu.edu.cn(2001:da8:1008:1::2)。
    2002::/16 6to4地址,用于6to4自动构造隧道技术的地址。

    3ffe::/16 早期开始的IPv6 6bone试验网地址

    注:上面三类属于单播地址,都是目前互联网上广泛应用的IPv6地址

    fe80::/10 本地链路地址,用于单一链路,适用于自动配置、邻机发现等,路由器不转发。类似于IPv4中的169.254.0.0/16。

    ff00::/8 组播地址

    ::A.B.C.D 其中<A.B.C.D>代表ipv4地址,兼容IPv4的IPv6地址。自动将IPv6包以隧道方式在IPv4网络中传送的IPv4/IPv6节点将使用这些地址,目前已经被取消。

    ::FFFF:A.B.C.D 其中<A.B.C.D>代表ipv4地址,例如 ::ffff:202.120.2.30 ,是IPv4映射过来的IPv6地址,它是在不支持IPv6的网上用于表示IPv4节点

    分享一个ipv6的工具网站

    https://www.ultratools.com/tools/ipv4toipv6

  • python执行shell命令

    在 python for unix and linux system administraton一书中,有这么一句话:

    You can run any shell command in Python just as it would be run with Bash.

    你可以用python执行bash中可以执行的任何命令。

    显示/tmp/信息(两种执行bash命令的方式)

    #!/usr/bin/env python
    import subprocess
    subprocess.call(["ls","-l","/tmp/"])
    subprocess.call("df -l /tmp/", shell=True)

    将输出赋给指定变量

    output = subprocess.check_output('ls', shell=True)