Python中的异常

如何引发异常

使用raise语句

>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
>>> 
>>> raise Exception("Unknown Error")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: Unknown Error

如何显示所有的内建异常

>>> import exceptions
>>> dir(exceptions) 

自定义异常

继承Exception这个异常的基类即可

>>> class CustomerException(Exception): pass    

如何捕捉异常

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 
>>> try:
...   1/0
... except ZeroDivisionError:
...   print("zero division error")
... 
zero division error

如何捕捉到异常并重新引发它

调用不带参数的raise

>>> try:
...   1/0
... except Exception:
...   print("got exception")
...   raise
... 
got exception
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero 

多个except子句

try:
  x = input("x:")
  y = input("y:")
  int(x)/int(y)
except ZeroDivisionError:
  print("division by zero {}/{}".format(x, y))
except ValueError:
  print("value error {}/{}".format(x, y))       

用一个块捕捉两个异常

try:
  x = input("x:")
  y = input("y:")
  int(x)/int(y)
except (ZeroDivisionError, ValueError) as e:
  print(e)
  print("error: {}/{}".format(x, y))

else

try:
  print("Hello World!")
except:
  print("Got Error!")
else:
  print("Everything is OK!")      

# Hello World!
# Everything is OK!

finally

Example 1:

try: 
  1/0
finally:
  print("Cleaning Up")  

'''   
Cleaning Up
Traceback (most recent call last):
  File "test4.py", line 2, in <module>
    1/0
ZeroDivisionError: division by zero
'''

Example 2:

try: 
  1/0
except:
  print("Unknow")
else:
  print("Well")
finally:
  print("Cleaning Up")

# Unknow
# Cleaning Up     

Python

这篇文章: 有用 无用
创建 2018-10-23 00:00:52 / 更新 2018-10-23 00:00:52

Python中的参数传递

基本参数

def hello(greeting, name):
    print('{0}, {1}!'.format(greeting, name))

hello("Hello", "World")

默认参数

def hello2(name="World", greeting="Hello"):
  print('{0}, {1}!'.format(greeting, name))

hello2() # Hello, World!
hello2("Noah") # Hello, Noah!
hello2(name="Noah") # Hello, Noah!
hello2(greeting="Hi") # Hi, World!
hello2("Beata", "Hi") # Hi, Beata!

收集参数

def print_params(*params):
   print(params)

print_params(1,2,3) # (1, 2, 3)

def print_params(title, *params):
    print(title)
    print(params) 

print_params("Title", 1, 2, 3) 
# Title
# (1, 2, 3)

def print_pair(**kp):
    print(kp)

print_pair(x=1, y=2, z=3) # {'x': 1, 'y': 2, 'z': 3}

def print_all(title, *params, **kp):
    print(title)
    print(*params)
    print(kp)

print_all("Title", 1, 2, 3, x=1, y=2, z=3)
# Title
# 1 2 3
# {'x': 1, 'y': 2, 'z': 3}      

反转参数

def add(x, y):
    'Add x and y and print it'
    print("{0}+{1}={2}".format(x, y, x+y))

add(4, 5)
nums = [4, 5]
add(*nums)

params = {"greeting": "Hi", "name": "Dear"}

hello(**params)
hello2(**params)

方法相关

print(callable(nums)) # False
print(callable(hello)) # True

print("-"*100)
print(add.__doc__)
print("-"*100)
help(add)
print("-"*100)  

Python

这篇文章: 有用 无用
创建 2018-10-16 23:45:05 / 更新 2018-10-16 23:45:05

Python中的基本操作

sys

import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
paths = sys.path # return lib paths

os

import os
os.system() # Execute a shell command
os.getcwd() # Returns the current working directory.
os.getgid() # Return the real group id of the current process.
os.getuid() # Return the current process’s user id.
os.getpid() # Returns the real process ID of the current process.
os.uname() # Return information identifying the current operating system.
os.chroot(path) # Change the root directory of the current process to path.
os.listdir(path) # Return a list of the entries in the directory given by path.
os.mkdir(path) # Create a directory named path with numeric mode mode.
os.makedirs(path) # Recursive directory creation function.
os.remove(path) # Remove (delete) the file path.
os.removedirs(path) # Remove directories recursively.
os.rename(src, dst) # Rename the file or directory src to dst.
os.rmdir(path) # Remove (delete) the directory path.

os.path

import os.path
os.path.isfile('my_settings.dat')
os.path.isdir('src')
os.path.exists('tumblr')

string

import string
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'

Python

这篇文章: 有用 无用
创建 2018-08-06 06:11:35 / 更新 2018-10-16 09:54:42

Python 文件操作

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Python 中的文件模式

Character Meaning
'r' open for reading (default)

'w' open for writing, truncating the file first
    If file does not exist, it creates a new file.

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of the file if it exists
    If file does not exist, it creates a new file.

'b' binary mode

't' text mode (default)

'+' open a disk file for updating (reading and writing)

'U' universal newlines mode (deprecated)

读取文件的全部内容

open("test.txt", mode="r", encoding='utf8').read()    

逐行读文件

filepath = 'test.txt'  
with open(filepath) as fp:  
    for cnt, line in enumerate(fp):
        print("Line {}: {}".format(cnt, line))

with open(filepath) as fp:
    for line in fp:
        print(line, end='')

向文件添加文本

filepath = 'test.txt'
with open(filepath, 'a') as wf:
    wf.write("hello world!\n")

"+"的应用

filepath = 'test.txt'
with open(filepath, 'a+') as wf:
    wf.write('hello, ')
    wf.seek(0)
    wf.write('world!') # If the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write
    wf.seek(0)
    content = wf.read()
    print(content)

参考:

python open


Python

这篇文章: 有用 无用
创建 2018-08-06 06:11:01 / 更新 2018-10-17 02:17:41

Python 字典

如何创建一个字典:

phonebook = {'foo': '324234', 'bar': '234324'}

person = dict('name' = 'Noah', 'age' = 18)

paddle = dict([('VISCARIA', 'butterfly'), ('CLIPPER WOOD', 'sitiga')])

len(phonebook) # 返回键值对的数量 2

person['name'] # 'Noah'

person['name'] = 'David'

del phonebook['foo'] # 删除键值为'foo'的项

'bar' in phonebook # 检查phonebook中是否有键为'bar'的项   

如何利用zip创建一个字典:

>>> a = [1,2,3]
>>> b = ['a', 'b', 'c', 'd']
>>> zip(a, b)
<zip object at 0x109c60a48>
>>> list(zip(a, b))
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> dict(zip(a,b))
{1: 'a', 2: 'b', 3: 'c'}

字典中键可以自动创建:

car = {}
car['brand'] = 'honda'

字典方法:

clear

d = {}
d['name'] = 'Moose'
d['age'] = 24
d.clear() # 清除字典中所有的项

fromkeys

>>> dict.fromkeys(['apple', 'orange'], 1)    
{'apple': 1, 'orange': 1}

get

>>> d = {}
>>> print(d['name'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'

>>> d = {}
>>> print(d.get('name'))
None
>>> print(d.get('name', 'N/A'))
N/A
>>> d['name'] = 'Noah'
>>> print(d.get('name', 'N/A'))
Noah

items / loop

>>> m
{'apple': 1, 'orange': 1}
>>> m.items()
dict_items([('apple', 1), ('orange', 1)])   
>>> for i in m.items():
...     print(i)
... 
('apple', 1)
('orange', 1)

>>> m = {'apple': 1, 'orange': 1}
>>> for k, v in m.items():
...   print('k: {}, v: {}'.format(k, v))
...
k: apple, v: 1
k: orange, v: 1

keys

person = {"age":30,"gender":"male","height":183,"weight":140}
person.keys()

values

person = {"age":30,"gender":"male","height":183,"weight":140}
person.values()

pop

>>> d = {'x':1, 'y':2, 'z':3}
>>> d.pop('y')
2
>>> d
{'x': 1, 'z': 3}    

update

>>> x = {1:'a', 2:'b'}
>>> x
{1: 'a', 2: 'b'}
>>> y = {1:'b', 3:'c'}
>>> x.update(y)
>>> x
{1: 'b', 2: 'b', 3: 'c'}

>>> person = {"name": "noah", "age": 30}
>>> person.update({"age": 32})
>>> person
{'name': 'noah', 'age': 32} 

sorted

d = {1:0,2:3,3:2,5:1}
sorted(d.items(), key=lambda x: x[0]) # sorted by key
sorted(d.items(), key=lambda x: x[1]) # sorted by value
sorted(d.items(), key=lambda x: x[1], reverse=True) # sorted by value desc

Python

这篇文章: 有用 无用
创建 2018-08-05 14:48:13 / 更新 2019-03-27 05:38:51

Python 列表和元组

列表和元组的主要区别是,列表可以修改,元组不能

如何定义一个列表:

pen_holder = ['pen', 'refill', 'bookmarks']

索引:

pen_holder[0] # pen
pen_holder[-1] # bookmarks

分片(前包含,后不包含):

pen_holder[0:2] # ['pen', 'refill']
pen_holder[-3:-1] # ['pen', 'refill']
pen_holder[-2:] # ['refill', 'bookmarks']
pen_holder[1:] # ['refill', 'bookmarks']
pen_holder[:] # ['pen', 'refill', 'bookmarks'] 复制一个列表,不会指向原列表

分片和步长(默认步长为1):

pen_holder[::2] # ['pen', 'bookmarks']
pen_holder[::-2] # ['bookmarks', 'pen'] # 步长为负,从右向左
pen_holder[::-1] # ['bookmarks', 'refill', 'pen'] # 数组反序

序列相加:

[1,2,3] + [4,5,6] # [1,2,3,4,5,6]

乘法:

[8] * 8 # [8,8,8,8,8,8,8,8]

初始化一个长度为10的列表:

seq = [None] * 10 # None是Python的一个内建值,表示“什么也没有”

成员资格:

'pen' in pen_holder # True
'spoon' in pen_holder # False

database = [
    ['albert', '1234'],
    ['noah', '2342'],
    ['json', '4565']
]                

['alert', '1234'] in database # True
['alert', '3423'] in database # False

长度,最小值,最大值:

len(pen_holder) # 3
min(pen_holder) # 'bookmarks'        
max(pen_holder) # 'refill'
min(1,2,3) # 1
max(1,2,3) # 3

list函数:

list('Big') # ['B', 'i', 'g']

元素赋值:

不能为一个位置不存在的元素进行赋值,如果列表长度为2,那么不能为索引为2的元素进行赋值。如果需要给索引为2的元素赋值,需要创建一个长度至少为3的列表。

pen_holder[0] = 'bottle opener'

删除元素:

del open_holder[0]

分片赋值:

可以使用与原长不等长的序列替换

name = list('Noah')
name[1:] = 'ikky' # ['N', 'i', 'k', 'k', 'y']

name = list('Big')
name[3:] = 'ger' # ['B', 'i', 'g', 'g', 'e', 'r'] # 在结尾插入
''.join(name) # Bigger  

name = list('word')
name[:0] = 's' # ['s', 'w', 'o', 'r', 'd']  

列表的方法

append

pen_holder.append('card')

pop

pen_holder.pop() # 'card'   

extend

pen_holder.extend(['key', 'charger'])

count

x = [[1,2], 1, 2, 1, [1,2,3]]    
x.count(1) # 2
x.count([1,2]) # 1

index

x = ['We', 'are', 'the', 'world']
x.index('are') # 1
x.index('work') # 异常

insert

x = [1,3,4,5]
x.insert(0, 0)
x.insert(2, 2) # [0, 1, 2, 3, 4, 5]

remove

移除列表中某个值的第一个匹配项

x = ['I', 'am', 'a', 'Chinese']
x.remove('a') 
x.remove('an') # 异常

reverse

将列表的元素反向存放

x = [1,2,3]
x.reverse()  

sort

x = [4,2,1,3,5]
x.sort # [1,2,3,4,5] 改变原列表

y = sorted(x) # 不会改变原列表            

Python

这篇文章: 有用 无用
创建 2018-06-21 00:13:01 / 更新 2018-06-21 00:13:01

Python中使用RSA加密解密

首先安装rsa包

pip install rsa

需要使用openssl生成private key

openssl genrsa -out key.pem 1024

再生成public key

openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem

然后就可以使用代码测试了

#/usr/bin/python
# -*- coding: utf-8 -*-

import rsa
from os.path import expanduser

home = expanduser("~")

with open(home+'/.ssh/key.pem', mode='rb') as privfile:
    keydata = privfile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata)

with open(home+'/.ssh/pubkey.pem', mode='rb') as pubfile:
    keydata = pubfile.read()
pubkey = rsa.PublicKey.load_pkcs1(keydata)

message = u'我是中国人'.encode('utf-8')
crypto = rsa.encrypt(message, pubkey)

icrypto = rsa.transform.bytes2int(crypto)
print(icrypto)
crypto = rsa.transform.int2bytes(icrypto)

message = rsa.decrypt(crypto, privkey)
print(message.decode('utf-8'))    

参考:

openssl generate public rsa key

rsa

RSA encryption and decryption

RSA int2bytes bytes2int


Python

这篇文章: 有用 无用
创建 2018-06-17 03:01:58 / 更新 2018-07-05 08:34:49