Category: Python

  • 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
  • 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)
  • python的入门的几个例子(上)

    在Python for Unix and Linux System Administration列出了几个选择python的理由:

    易入门

    上手后可进行系统管理
    能解决复杂问题
    代码简洁,易读
    关键字使陌生代码易读
    面向对象
    社区优秀
    很好的标准库

    python的基础例子在这里,很有意思,下一个例子的行数是递增的

    http://wiki.python.org/moin/SimplePrograms

    例1.输出显示–Output

    print 'Hello world'

    例2.变量以提示输入的方式赋值,并打印出来–Input, assignment

    name = raw_input('What is your name?\n')
    print 'Hi, %s.' % name

    例3.for循环,内置的列举函数,format格式–For loop, built-in enumerate function, new style formatting

    friends = ['jhon', 'pat', 'gary', 'micheal']
    for i, name in enumerate(friends):
        print "iteration {iteration} is {name}".format(iteration=i, name=name)

    例4.斐波纳契,元组的赋值–Fibonacci, tuple assignment

    parents, babies = (1, 1)
    while babies < 100:
        print 'This generation has {0} babies'.format(babies)
        parents, babies = (babies, parents + babies)

    例5.函数–Functions

    def greet(name):
        print 'hello', name
    greet('Jack')
    greet('Jill')
    greet('Bob')

    例6.import,正则表达式–Import, regular expressions。这里是匹配3位数字-4位数字的字符串。

    import re
    for test_string in [ '555-1212', 'ILL-EGAL' ]:
        if re.match(r'^\d{3}-\d{4}', test_string):
            print test_string, 'is a valid US local phone number'
        else:
            print test_string, 'rejected'

    例7.字典,生成表达式–Dictionaries, generator expressions

    prices = { 'apple': 0.40, 'banana': 0.50 }
    my_purchase = {
        'apple': 1,
        'banana':6}
    grocery_bill = sum(prices[fruit] * my_purchase[fruit]
                       for fruit in my_purchase)
    print 'I owe the grocer $%.2f' % grocery_bill

    例8.调用命令参数,异常处理–Command line arguments, exception handling

    #!/usr/bin/env python
    # This program adds up integers in the command line
    import sys
    try:
        total = sum(int(arg) for arg in sys.argv[1:])
        print 'sum =', total
    except ValueError:
        print 'Please supply integer arguments'

    上面是将跟的参数相加,如果不是整数,则提示需输入整数

    $ python se8.py 1 2 3 4 5 6
    sum = 21
    $ python se8.py 1 2 3 4 5 a
    Please supply integer arguments

    例9.打开文件–Opening files

    # indent your Python code to put into an email
    import glob
    # glob supports Unix style pathname extensions
    python_files = glob.glob('*.py')
    for file_name in sorted(python_files):
    print ' ------' + file_name
    
    with open(file_name) as f:
    for line in f:
    print ' ' + line.rstrip()
    
    print

    例10.时间,条件,from..import,for ..else循环 — Time, conditionals, from..import, for..else

    from time import localtime
    
    activities = {8: 'Sleeping',
                  9: 'Commuting',
                  17: 'Working',
                  18: 'Commuting',
                  20: 'Eating',
                  22: 'Resting' }
    
    time_now = localtime()
    hour = time_now.tm_hour
    
    for activity_time in sorted(activities.keys()):
        if hour < activity_time:
            print activities[activity_time]
            break
    else:
        print 'Unknown, AFK or sleeping!'

    整理一些小知识

    段落注释的方法

    """ """

     

  • python开启debug模式

    两种方式:

    app.debug = Ture
    app.run

    或者是

    app.run(debug = True)
  • python非英文国家编码问题

    python运行错误

    File "ex3.py", line 1
    SyntaxError: Non-ASCII character '\xe5' in file ex3.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

    我只是在注释里加了中文,同样错误,现在在python脚本的头部加入

    # -- coding: utf-8 --

    这样就使用了utf-8编码,就不会出错了。

     

  • python中DNS查询和反向查询

    用到的还是python的socket库,用到函数getaddrinfo()

    定义如下:

    getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)
    例:

    #!/usr/bin/env python
    import sys, socket
    result = socket.getaddrinfo("jpuyy.com", 80, 0, 0, socket.SOL_TCP)
    print result

    返回结果是

    [(10, 1, 6, ”, (‘2604:6600:1059::5810:3a0a’, 80, 0, 0)), (2, 1, 6, ”, (‘216.24.201.107’, 80))]

    执行反向查询

    gethostbyaddr(ip_address)

    查询主机名的详细信息

    getfqdn([name])   #Return a fully qualified domain name for name.

    http://docs.python.org/library/socket.html

    在debian下面安装PyDNS( python-dns )进行DNS的高级查询

    apt-get install python-dns

    程序中,import DNS,先进行 DNS.DiscoverNameServers(),然后建立一个请求对象 DNS.Request()。请求后PyDNS会返回包含结果的对象。