Python语句
>>> 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'
? ? ?本文轉自hj_1314wgn 51CTO博客,原文鏈接:http://blog.51cto.com/13513556/2054083,如需轉載請自行聯系原作者
總結
- 上一篇: Android第二十期 - 微信的主体构
- 下一篇: LoadRunner11设置场景百分比模