Python语句

发布时间:2019-08-28 09:07:53编辑:auto阅读(1433)

    >>> range(10)  #表示一段范围,起始不写表示从0开始,结束不包含

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    >>> range(1, 11)

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    >>> range(5, 11)

    [5, 6, 7, 8, 9, 10]

    >>> range(1, 11, 2) #起始写了表示从起始开始,后面的11不包含,2表示步长值

    [1, 3, 5, 7, 9]

    >>> range(2, 11, 2)

    [2, 4, 6, 8, 10]

    >>> range(10, 0, -1)

    [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]



    列表解析

    >>> [10]

    [10]

    >>> [20 + 20]

    [40]

    >>> [10 + 10 for i in range(5)]

    [20, 20, 20, 20, 20]

    >>> [10 + i for i in range(5)]

    [10, 11, 12, 13, 14]

    >>> [10 + i for i in range(1, 11)]

    [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

    >>> [10 + i for i in range(1, 11) if i % 2 == 1]#把列表中的基数解析出来

    [11, 13, 15, 17, 19]

    >>> [10 + i for i in range(1, 11) if i % 2 == 0]#把列表中的偶数解析出来

    [12, 14, 16, 18, 20]

    >>> ['192.168.1.%s' % i for i in range(1, 5)]

    ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4'] #ip地址表示方法




    文件读取方法:

    >>> f = open('/etc/passwd')

    >>> data = f.read()

    >>> f.close()

    >>> data

    >>> print data

    >>> f = open('/etc/passwd') #常用for循环语句读取数据

    >>> for line in f:

    ...   print line,


    >>> f = open('/tmp/hello.txt', 'w')

    >>> 

    >>> f.write('hello the world')

    >>> f.flush()

    >>> f.write("\n")

    >>> f.flush()

    >>> f.write('33333333\n')

    >>> f.flush()

    >>> f.writelines(['aaa\n', '3rd line\n'])

    >>> f.flush()


    f1 = open('/bin/ls')

    f2 = open('/root/ls', 'w')


    data = f1.read()

    f2.write(data)


    f1.close()

    f2.close()

    md5sum /bin/ls /root/ls #产看两个文件的属性是否相同,用md5sum查看 


    def gen_fibs(l):  #定义函数用def gen_fibs()

        fibs = [0, 1]

        for i in range(l-2):

            fibs.append(fibs[-1] + fibs[-2])

        return fibs

    a = int(raw_input('length: '))

    print gen_fibs(a)  #调用函数

    print gen_fibs(20)








    try:

        num = int(raw_input("number: "))

        result = 100 / num


    except ValueError:

        print 'You must input a number'

    except ZeroDivisionError:

        print '0 is not allowed'

    except (KeyboardInterrupt, EOFError):

        print '\nBye-bye'

    else:

        print result #出现异常才会打印

    finally:

        print 'Done' #不管出不出现异常最终都会输出Done



    def set_age(name, age):

        if not 0 < age < 150:

            raise ValueError, 'age out of range' #相当于主动触发异常,用关键字raise,后面跟要引发的异常的名称

        print '%s is %s years old' % (name, age)



    def set_age2(name,age):

        assert 0 < age < 150, 'age out of range' #断言异常的肯定,用关键字assert

        print '%s is %s years old' % (name, age)

    if __name__ == '__main__':

        set_age('hanjie', 22)

        set_age2('hanjie', 220)


    >>> with open('/etc/passwd') as f:

    ...     f.readline()

    ... 

    'root:x:0:0:root:/root:/bin/bash\n'




    正则表达式:%s/\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1:\2:\3:\4:\5:\6/

    192.168.1.1      00000ac15658   #没有转换之前

    192.168.1.2      5253000a1234

    192.168.1.3      5356afc35695

    192.168.1.1      00:00:0a:c1:56:58 #转化之后

    192.168.1.2      52:53:00:0a:12:34

    192.168.1.3      53:56:af:c3:56:95


    查看用户日志:

    import re

    def count_patt(fname, patt):

        result = {}

        cpatt = re.compile(patt)

        fobj = open(fname)

        for line in fobj:

            m = cpatt.search(line)

            if m:

                key = m.group()

                if key not in result:

                    result[key] = 1

                else:

                    result[key] += 1

            fobj.close()

            return result

    if __name__ == '__main__':

        fname = 'access_log'

        ip_patt = '^(\d+\.){3}\d+'

        br_patt = 'Firefox|MISE|Chrome'

        print count_patt(fname, ip_patt)

        print count_patt(fname, br_patt)

    Python中使用的快捷方式'tab'键

    vim /usr/local/bin/tab.py

    from rlcompleter import readline

    readline.parse_and_bind('tab: complete')

    vim ~/.bashrc

    export PYTHONSTARTUP=/usr/local/bin/tab.py

    source .bashrc




    用Python编程创建用户:

    import sys

    import subprocess

    import randpass

    def adduser(username, fname):

        password = randpass.gen_pass()

        info = """user information:

        username: %s

        password: %s"""

        subprocess.call('useradd %s' % username, shell=True)

        subprocess.call('echo %s | passwd --stdin %s' % (password, username), shell=True)

        with open(fname, 'a') as fobj:

            fobj.write(info % (username, password))

    if __name__ == '__main__':

        adduser(sys.argv[1], '/tmp/user.txt')


    Python编程在以网段内有多少个主机是开着的:如下

    import subprocess

    import threading

    def ping(host):

        result = subprocess.call('ping -c2 %s &> /dev/null' % host, shell=True)

        if result == 0:

            print '%s: up' % host

        else:

            print '%s: down' % host

    if __name__ == '__main__':

        ips = ['176.130.8.%s' % i for i in range(1, 255)]

        for ip in ips:

            t = threading.Thread(target=ping, args=[ip]) #调用多线成模块

            t.start()

    多线程实现ssh并发访问:       

    import threading

    import getpass

    import paramiko

    import sys

    import os

    def remote_comm(host, pwd, command):

        ssh = paramiko.SSHClient()

        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh.connect(host, username= 'root', password= pwd)

        stdin, stdout, stderr = ssh.exec_command(command)

        out = stdout.read()

        error = stderr.read()

        if out:

            print "[out] %s: \n%s" %(host, out),

        if error:

            print "[error] %s: \n%s" %(host, error),

            ssh.close()

    if __name__ == '__main__':

        if len(sys.argv) != 3:

            print "Usage: %s ipfile 'command'" % sys.argv[0]

            sys.exit(1)

        ipfile = sys.argv[1]

        command = sys.argv[2]

        if not os.path.isfile(ipfile):

            print "No such file:", ipfile

            sys.exit(2)

        pwd = getpass.getpass("password:")

        with open(ipfile) as fobj:

            for line in fobj:

                ip = line.strip()

                t = threading.Thread(target=remote_comm, args=(ip, pwd, command))

                t.start()


    剪刀石头布当输入错误时会引发,一些错误提示

    pwin = 0  #人赢的次数

    cwin = 0  #电脑赢得次数

    import random

    all_choices = ['石头', '剪刀', '布']

    win_list = [['石头', '剪刀'], ['剪刀', '布'], ['石头', '布']]

    prompt = """(0)石头

    (1)剪刀

    (2)布

    请选择(0/1/2):"""

    while pwin < 2 and cwin < 2:

        computer = random.choice(all_choices)


        try:

            ind = int(raw_input(prompt))

            player = all_choices[ind]

        except (ValueError, IndexError):

            print 'Inavlid input. Try again'

            continue

        except (KeyboardInterrupt, EOFError):

            print '\nBye-bye'

            break


        print "Your choice: %s, Computer's choice: %s" %(player, computer)

        if player == computer:

            print '\033[32;1m平局\033[0m'

        elif [player,computer] in win_list:

            pwin += 1

            print '\033[31;1m你赢了\033[0m'

        else:

            cwin += 1

            print '\033[31;1m你输了\033[0m'




关键字

上一篇: python expect

下一篇: 在windows上安装Python cr