python learning: the use of several functions implementation example

1, python program exit in several ways

import sys
sys.exit()
sys.exit(0)
sys.exit(1)

或者
os._exit()

该方法中包含一个参数status,默认为0,表示正常退出,也可以为1,表示异常退出

2. python achieve access to computer IP, host name, Mac address

import socket
import uuid

# 获取主机名
hostname = socket.gethostname()
#获取IP
ip = socket.gethostbyname(hostname)
# 获取Mac地址
def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0,11,2)])

# ipList = socket.gethostbyname_ex(hostname)
# print(ipList)
print("主机名:",hostname)
print("IP:",ip)
print("Mac地址:",get_mac_address())

3. aes encryption

import base64
from Crypto.Cipher import AES

'''
采用AES对称加密算法
'''
# str不是16的倍数那就补足为16的倍数
def add_to_16(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)  # 返回bytes
#加密方法
def encrypt_oracle():
    # 秘钥
    key = '123456'
    # 待加密文本
    text = 'abc123def456'
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    #先进行aes加密
    encrypt_aes = aes.encrypt(add_to_16(text))
    #用base64转成字符串形式
    encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8')  # 执行加密并转码返回bytes
    print(encrypted_text)
#解密方法
def decrypt_oralce():
    # 秘钥
    key = '123456'
    # 密文
    text = 'qR/TQk4INsWeXdMSbCDDdA=='
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    #优先逆向解密base64成bytes
    base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
    #执行解密密并转码返回str
    decrypted_text = str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0','') 
    print(decrypted_text)

if __name__ == '__main__':
   # encrypt_oracle()
    decrypt_oralce()

4, python string taken

str = ‘0123456789’
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取,具体啥意思没搞明白?

对应输出结果:
012
0123456789
6789
0123456
2
9
9876543210
78
789
96

5, Python get the current path to the user's home directory, the following sample code:

import os

print (os.environ['HOME'])
print (os.path.expandvars('$HOME'))
print (os.path.expanduser('~'))

Guess you like

Origin www.cnblogs.com/panie2015/p/12082979.html