Author: jpuyy

  • Ubuntu下安装Django

    Django为流行的python web开发框架

    安装python的包管理器,easy_install

    # apt-get install python-setuptools

    可以使用下面的命令检查是否安装成功

    # easy_install --version

    显示版本信息则安装成功

    接下来使用easy_install安装Django

    # easy_install django

    使用如下命令查看django是否安装成功

    # python
    Python 2.7.3 (default, Aug 1 2012, 05:14:39)
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import django
    >>> django.VERSION
     (1, 4, 3, 'final', 0)

    出现版本信息,则表示安装成功。

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

    http://jpuyy.com/2012/12/python-simple-programs-a.html

    http://jpuyy.com/2013/01/python-simple-programs-b.html

    例.20 素数筛选,生成器–Prime numbers sieve w/fancy generators

    生成从2到1000以内的素数

    import itertools
    
    def iter_primes():
         # an iterator of all numbers between 2 and +infinity
         numbers = itertools.count(2)
    
         # generate primes forever
         while True:
             # get the first number from the iterator (always a prime)
             prime = numbers.next()
             yield prime
    
             # this code iteratively builds up a chain of
             # filters...slightly tricky, but ponder it a bit
             numbers = itertools.ifilter(prime.__rmod__, numbers)
    
    for p in iter_primes():
        if p > 1000:
            break
        print p

    例21.xml/html解析–XML/HTML parsing

    dinner_recipe = '''<html><body><table>
    <tr><th>amt</th><th>unit</th><th>item</th></tr>
    <tr><td>24</td><td>slices</td><td>baguette</td></tr>
    <tr><td>2+</td><td>tbsp</td><td>olive oil</td></tr>
    <tr><td>1</td><td>cup</td><td>tomatoes</td></tr>
    <tr><td>1</td><td>jar</td><td>pesto</td></tr>
    </table></body></html>'''
    
    # In Python 2.5 or from http://effbot.org/zone/element-index.htm
    import xml.etree.ElementTree as etree
    tree = etree.fromstring(dinner_recipe)
    
    # For invalid HTML use http://effbot.org/zone/element-soup.htm
    # import ElementSoup, StringIO
    # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe))
    
    pantry = set(['olive oil', 'pesto'])
    for ingredient in tree.getiterator('tr'):
        amt, unit, item = ingredient
        if item.tag == "td" and item.text not in pantry:
            print "%s: %s %s" % (item.text, amt.text, unit.text)

    例28. 8皇后问题(自定义例外)8-Queens Problem (define your own exceptions)

    BOARD_SIZE = 8
    
    class BailOut(Exception):
        pass
    
    def validate(queens):
        left = right = col = queens[-1]
        for r in reversed(queens[:-1]):
            left, right = left-1, right+1
            if r in (left, col, right):
                raise BailOut
    
    def add_queen(queens):
        for i in range(BOARD_SIZE):
            test_queens = queens + [i]
            try:
                validate(test_queens)
                if len(test_queens) == BOARD_SIZE:
                    return test_queens
                else:
                    return add_queen(test_queens)
            except BailOut:
                pass
        raise BailOut
    
    queens = add_queen([])
    print queens
    print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)
     例33,猜数字游戏
    import random
    
    guesses_made = 0
    
    name = raw_input('Hello! What is your name?\n')
    
    number = random.randint(1, 20)
    print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name)
    
    while guesses_made < 6:
    
        guess = int(raw_input('Take a guess: '))
    
        guesses_made += 1
    
        if guess < number:
            print 'Your guess is too low.'
    
        if guess > number:
            print 'Your guess is too high.'
    
        if guess == number:
            break
    
    if guess == number:
        print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)
    else:
        print 'Nope. The number I was thinking of was {0}'.format(number)
     把代码打了一遍,还得仔细再练几遍。
  • 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