1. 程式人生 > >python 常用模塊練習題&總結

python 常用模塊練習題&總結

位數 access 封裝 error exit some balance 實現 shell

# 1、logging模塊有幾個日誌級別?

 logging模塊共有5個級別,分別是:
 DEBUG INFO WARNING ERROR CRITICAL
logging的日誌可以分為 debug(), info(), warning(), error(){  /‘?r?/ and critical()5個級別
#2 請配置logging模塊,使其在屏幕和文件裏同時打印以下格式的日誌
#2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts

#將日誌同時輸出到屏幕和日誌文件
import
logging #logger提供了應用程序可以直接使用的接口; logger = logging.getLogger(access) logger.setLevel(level = logging.INFO) #handler將(logger創建的)日誌記錄發送到合適的目的輸出; # FileHandler()輸出至文件 handler = logging.FileHandler("log.txt") handler.setLevel(logging.ERROR) # StreamHandler()輸出至屏幕 console = logging.StreamHandler() console.setLevel(logging.ERROR)
#增加指定的Handler logger.addHandler(handler) logger.addHandler(console) #formatter決定日誌記錄的最終輸出格式。 formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s) handler.setFormatter(formatter) #logger.info("Start print log") logger.error("account [1234] too many login attempts")
#logger.warning("Something maybe fail.") #logger.info("Finish")
3、json、pickle、shelve三個區別是什麽?

 首先,這三個模塊都是序列化工具。

 1. json是所有語言的序列化工具,優點跨語言、體積小.只能序列化一些基本的數據類型。int\str\list\tuple\dict

 pickle是python語言特有序列化工具,所有數據都能序列化。只能在python中使用,存儲數據占空間大.

 shelve模塊是一個簡單的k,v(健值對)將內存數據通過文件持久化的模塊,可以持久化任何pickle可支持的python數據格式。

 2. 使用方式,json和pickle用法一樣,
shelve是f =shelve.open(shelve_test)
4、json的作用是什麽?

 功能:序列化是指把內存裏的數據類型轉變成字符串,以使其能存儲到硬盤或通過網絡傳輸到遠程,因為硬盤或網絡傳輸時只能接受bytes(二進制)

json,用於字符串和python數據類型間進行轉換

pickle,用於python特有的類型和python的數據類型間進行轉換
5、subprocess
即允許你去創建一個新的進程讓其執行另外的程序,並與它進行通信,獲取標準的輸入、標準輸出、標準錯誤以及返回碼等。
註意:使用這個模塊之前要先引入該模塊。


我們經常需要通過Python去執行一條系統命令或腳本,系統的shell命令是獨立於你的python進程之外的,
每執行一條命令,就是發起一個新進程,通過python調用系統命令或腳本的模塊在python2有os.system,
除了os.system可以調用系統命令,,commands,popen2等也可以,比較亂,

於是官方推出了subprocess,目地是提供統一的模塊來實現對系統命令或腳本的調用

三種執行命令的方法

  • subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推薦

  • subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面實現的內容差不多,另一種寫法

  • subprocess.Popen() #上面各種方法的底層封裝

整個概念不理解!!!

6、為什麽要設計好目錄結構?

1.可讀性高: 不熟悉這個項目的代碼的人,一眼就能看懂目錄結構,知道程序啟動腳本是哪個,測試目錄在哪兒,配置文件在哪兒等等。從而非常快速的了解這個項目。

2.可維護性高: 定義好組織規則後,維護者就能很明確地知道,新增的哪個文件和代碼應該放在什麽目錄之下。
這個好處是,隨著時間的推移,代碼/配置的規模增加,項目結構不會混亂,仍然能夠組織良好。

7、打印出命令行的第一個參數。例如:

python argument.py luffy
打印出 luffy

在腳本裏面寫入:
from sys import argv
script,name = argv
print(name)

在命令行裏輸入:

先進入腳本所在目錄
D:\> python argument.py luffy

輸出 luffy

8、
在當前目錄下的D:/Pycharm/demo/LuFei/第二模塊/第二章/練習題/argument.py
文件名:/argument.py
‘‘‘
import os

# 獲取路徑名:os.path.dirname()
# 獲得絕對路徑: os.path.abspath()

BASE_DIR = os.path.abspath(‘argument.py‘) #文件的絕對路徑
BASE_DIR2 = os.path.dirname(os.path.abspath(‘argument.py‘))
BASE_DIR3 = os.path.dirname(os.path.dirname(os.path.abspath(‘argument.py‘)))
BASE_DIR4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(‘argument.py‘))))

print(BASE_DIR)
print(BASE_DIR2)
print(BASE_DIR3)
print(BASE_DIR4)


打印內容:
D:\Pycharm\demo\LuFei\第二模塊\第二章\練習題\argument.py
D:\Pycharm\demo\LuFei\第二模塊\第二章\練習題
D:\Pycharm\demo\LuFei\第二模塊\第二章
D:\Pycharm\demo\LuFei\第二模塊


打印的內容是什麽?
os.path.dirname和os.path.abspath含義是什麽?

9、通過configparser模塊完成以下功能:
文件名my.cnf.ini

[DEFAULT]

[client]
port = 3306
socket = /data/mysql_3306/mysql.sock

[mysqld]
explicit_defaults_for_timestamp = true
port = 3306
socket = /data/mysql_3306/mysql.sock
back_log = 80
basedir = /usr/local/mysql
tmpdir = /tmp
datadir = /data/mysql_3306
default-time-zone = +8:00
-----------------------------------------

import configparser
config =configparser.ConfigParser() #初始化實例
config.read(my.cnf.ini)#讀取配置文件
print(config.sections())#讀取模塊名到列表中,也就是[]中的內容

print(config.default_section)
>[client, mysqld]

# 修改時區 default-time-zone = ‘+8:00‘ 為 校準的全球時間 +00:00
config[mysqld][default-time-zone] = +00:00
config.write(open(my.cnf.ini,w))

# 刪除 explicit_defaults_for_timestamp = true
config.remove_option(mysqld,explicit_defaults_for_timestamp = true)
config.write(open(my.cnf.ini,w))

# 為DEFAULT增加一條 character-set-server = utf8
config[DEFAULT][character-set-server] = utf8
config.write(open(my.cnf.ini,w))

----------------------------------------------
拓展:
#讀取指定sections內的所有key
print(se_keys:,config.options(mysqld))
#獲取指定sections的配置信息
print(config.items(mysqld))
#在指定的sections中通過key找出value
#通過get
print(config.get(mysqld,back_log ))
10、寫一個6位隨機驗證碼程序(使用random模塊),要求驗證碼中至少包含一個數字、一個小寫字母、一個大寫字母.

def choice():
    global ran1,ran2,ran3
    ran1 = random.randint(0,9) # randint()頭尾都包括
    ran2 = chr(random.randint(65,90))# 大寫
    ran3 = chr(random.randint(97,122))# 小寫
def random_num():
    global code
    code = ‘‘
    for i in range(3):#生成為3位數的驗證碼
        choice()
        add = random.choice([ran1,ran2,ran3])
        code = ‘‘.join([code,str(add)])
    return code
import random
choice()
code2 =‘‘.join([str(ran1),str(ran2),str(ran3)])
random_num()
print(‘‘.join([code2,code]))

---------------------------------------------------------------
#使用 string模塊
# 在大、小寫、數字中隨機返回6位數
import string,random
s = ‘‘.join(random.sample(string.ascii_letters + string.digits, 3))
ran1 = random.randint(0,9) # randint()頭尾都包括
ran2 = chr(random.randint(65,90))# 大寫
ran3 = chr(random.randint(97,122))# 小寫
code =‘‘.join([str(ran1),str(ran2),str(ran3)])
print(‘‘.join([code,s]))

11、利用正則表達式提取到 luffycity.com ,內容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>luffycity.com</title>
</head>
<body>
</body>
</html>

import re
f = open(index.html,r,encoding=utf-8)
data = f.read()
print(re.findall(luffycity.com,data))

12、寫一個用戶登錄驗證程序,文件如下 1234.json
{"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
 
用戶名為json文件名,密碼為 password。
判斷是否過期,與expire_date進行對比。
登陸成功後,打印“登陸成功”,三次登陸失敗,status值改為1,並且鎖定賬號。

import json,time,datetime
username = 1234.json
#首次登入將數據寫入文件
# data = {"expire_date": "2020-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
# with open(‘1234.json‘,‘r+‘,encoding=‘utf-8‘) as f:
#     file = json.dump(data,f)
with open(1234.json, r+, encoding=utf-8) as f2:
    file2 = json.load(f2)

print(請登錄用戶名、密碼進行驗證:)

count = 3
while count > 0:
    user_name = input(name:>).strip()
    pass_word = input(password:>).strip()
    if file2[status] == 1:
        print(該用戶已鎖定)
        exit()
    else:
        time_now = time.strftime(%Y-%m-%d)
        d1 = datetime.datetime.strptime(file2[expire_date], %Y-%m-%d)
        d2 = datetime.datetime.strptime(time_now, %Y-%m-%d)
        if d1 > d2:
            if user_name == username:
                if pass_word == file2[password]:
                    print(登錄成功)
                    exit()
                else:
                    count -= 1
                    print(f"您還有{count}次機會輸入")
                    if count == 0:
                        file2[status] = 1
                        with open(1234.json, w, encoding=utf-8) as f3:
                            json.dump(file2,f3)
                            break

            else:
                print(用戶名不存在:)
                continue

        else:
            print(已過期)
            break

13、把第12題三次驗證的密碼進行hashlib加密處理。即:json文件保存為md5的值,然後用md5的值進行驗證。

import hashlib
file2 = {"expire_date": "2020-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
hash_pass = file2[password]
m5 = hashlib.md5()
pass_data= m5.update(b"hash_pass")
#print(m5.digest(),type(m5.digest()))
#print(m5.hexdigest())

pass_word = input(>)
pass_input = m5.update(bpass_word)
if pass_input == pass_data:
    print(nice)

14、最近luffy買了個tesla,通過轉賬的形式,並且支付了5%的手續費,tesla價格為75萬。文件為json,請用程序實現該轉賬行為。 需求如下:

.
├── account
│ ├── luffy.json
│ └── tesla.json
└── bin
└── start.py

當執行start.py時,出現交互窗口

  ------- Luffy Bank ---------
  1. 賬戶信息
  2. 轉賬
選擇1 賬戶信息 顯示luffy的當前賬戶余額。
選擇2 轉賬 直接扣掉75萬和利息費用並且tesla賬戶增加75萬


import json,os,sys

#取出當前文件的目錄dir,
#當前文件父目錄
os.path.dirname(dir)
print(__file__)
dir = os.path.abspath(__file__)
dir2 = os.path.dirname(os.path.dirname(dir))
# 取出json文件的絕對路徑
file_path1 = dir2 + "\\" + "account" + "\\" + "luffy.json"
file_path2 = dir2 + "\\" + "account" + "\\" + "tesla.json"
print("""
------- Luffy Bank ---------
1. 賬戶信息
2. 轉賬
""")
while True:

    choice = input("""
請選擇如下序號:
1. 賬戶信息
2. 轉賬
q.退出
>
""")
    #  此題前提在luffy 下存入100萬
    with open(file_path1, r, encoding=utf-8) as f:
        balance = json.load(f)
    if choice == 1:
            print(f當前余額:{balance}萬)
            continue
    if choice == 2:
        balance = balance - balance*0.05 - 75
        tesla_balance = 75
        print(f"購買tesla共花費{balance - balance*0.05 - 75},tesla賬戶增加{tesla_balance}")
        with open(file_path2,w,encoding=utf-8) as f2:
           json.dump(tesla_balance,f2)
        with open(file_path1, w, encoding=utf-8) as f3:
           json.dump(balance, f3)
           continue

    elif choice == q:
        exit()

提現:
對上題增加一個需求:提現。 目錄結構如下

.
├── account
│ └── luffy.json
├── bin
│ └── start.py
└── core
└── withdraw.py
當執行start.py時,出現交互窗口

  ------- Luffy Bank ---------
  1. 賬戶信息
  2. 提現
選擇1 賬戶信息 顯示luffy的當前賬戶余額和信用額度。
選擇2 提現 提現金額應小於等於信用額度,利息為5%,提現金額為用戶自定義。

import json,os,sys

#取出當前文件的父目錄,
print(__file__)
dir = os.path.abspath(__file__)
dir2 = os.path.dirname(os.path.dirname(dir))
# 取出json文件的絕對路徑
file_path1 = dir2 + "\\" + "account" + "\\" + "luffy.json"
file_path2 = dir2 + "\\" + "account" + "\\" + "tesla.json"
print("""
------- Luffy Bank ---------
1. 賬戶信息
2. 提現
""")
data = {balance: 100, credit: 50}
with open(file_path1, w, encoding=utf-8) as f:
    json.dump(data,f)
while True:

    choice = input("""
請選擇如下序號:
1. 賬戶信息
2. 提現
q.退出
>
""")
    #  此題前提在luffy 下存入data字典信息
    #data = {‘balance‘: 100, ‘credit‘: 50}
    with open(file_path1, r, encoding=utf-8) as f:
        #json.dump(data,f)
        balance = json.load(f)
    if choice == 1:

        print(f"當前余額:{balance[‘balance‘]}萬,信用額度:{balance[‘credit‘]}萬")
        continue
    if choice == 2:
        withdraw_money = int(input(請輸入提現金額:).strip())
        if withdraw_money > balance[credit]:
            print(f"提現金額超過信用額度:{balance[‘credit‘]}萬,請重新輸入")
        else:
            balance[balance] = balance[balance] - withdraw_money - withdraw_money*0.05
            print(f"剩下余額{ balance[‘balance‘]}")
        with open(file_path1, w, encoding=utf-8) as f2:
           json.dump(balance, f2)
           continue

    elif choice == q:
        exit()

加登裝飾器

import json,os,sys

#取出當前文件的父目錄,
print(__file__)
dir = os.path.abspath(__file__)
dir2 = os.path.dirname(os.path.dirname(dir))
# 取出json文件的絕對路徑
file_path1 = dir2 + "\\" + "account" + "\\" + "luffy.json"
file_path2 = dir2 + "\\" + "account" + "\\" + "tesla.json"
global withdraw,transfer
print("""
------- Luffy Bank ---------
1. 賬戶信息
2. 提現
""")
# data = {‘balance‘: 100, ‘credit‘: 50}
# with open(file_path1, ‘w‘, encoding=‘utf-8‘) as f:
#     json.dump(data,f)
user_status = False
def login(fun):
    def inner(*args,**kwargs):
        user_name = xiao
        pass_word = 123
        global user_status
        if user_status == False:
            username = input(user:>).strip()
            password = input(password:>).strip()
            if username == user_name and pass_word == password:
                print(welcome login...)
                user_status = True
            else:
                print(wrong username or passerword)
        if user_status == True:
            return fun(*args,**kwargs)
    return inner

@login
def transfer():
    tesla_balance = 75
    balance[balance] = balance[balance] - tesla_balance * 0.05 - 75

    print(f"購買tesla共花費{tesla_balance * 0.05 + 75},tesla賬戶增加{tesla_balance}")
    with open(file_path2, w, encoding=utf-8) as f2:
        json.dump(tesla_balance, f2)
    with open(file_path1, w, encoding=utf-8) as f3:
        json.dump(balance, f3)
@login
def withdraw():
    withdraw_money = int(input(請輸入提現金額:).strip())
    if withdraw_money > balance[credit]:
        print(f"提現金額超過信用額度:{balance[‘credit‘]}萬,請重新輸入")
    else:
        balance[balance] = balance[balance] - withdraw_money - withdraw_money*0.05
        print(f"剩下余額{ balance[‘balance‘]}")
    with open(file_path1, w, encoding=utf-8) as f2:
       json.dump(balance, f2)

---------------------------------主函數-----------------------------------------
while True:

    choice = input("""
請選擇如下序號:
1. 賬戶信息
2. 提現
3.轉賬
q.退出
>
""")
    #  此題前提在luffy 下存入data字典信息
    # data = {‘balance‘: 100, ‘credit‘: 50}
    with open(file_path1, r, encoding=utf-8) as f:
        # json.dump(data,f)
        balance = json.load(f)
    if choice == 1:
        print(f"當前余額:{balance[‘balance‘]}萬,信用額度:{balance[‘credit‘]}萬")
        continue

    if choice == 2:
        withdraw()
        continue

    if choice == 3:
        transfer()
        continue
    elif choice == q:
        exit()
加日誌功能

對第15題的用戶轉賬、登錄、提現操作均通過logging模塊記錄日誌,日誌文件位置如下

.
├── account
│ └── luffy.json
├── bin
│ └── start.py
└── core
| └── withdraw.py
└── logs
└── bank.log

import json,os,sys

#取出當前文件的父目錄,
print(__file__)
dir = os.path.abspath(__file__)
dir2 = os.path.dirname(os.path.dirname(dir))
# 取出json文件的絕對路徑
file_path1 = dir2 + "\\" + "account" + "\\" + "luffy.json"
file_path2 = dir2 + "\\" + "account" + "\\" + "tesla.json"
#bank.logs絕對路徑
file_path3 = os.path.dirname(dir)+"\\" + "bank.log"

global withdraw,transfer

#日誌
# 將日誌同時輸出到屏幕和日誌文件
import logging
#logger提供了應用程序可以直接使用的接口;
logger = logging.getLogger(wed)
logger.setLevel(level = logging.INFO)
#handler將(logger創建的)日誌記錄發送到合適的目的輸出;
# FileHandler()輸出至屏幕
handler = logging.FileHandler(file_path3)
handler.setLevel(logging.INFO)
#formatter決定日誌記錄的最終輸出格式。
formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
handler.setFormatter(formatter)
# StreamHandler()輸出至屏幕
console = logging.StreamHandler()
console.setLevel(logging.INFO)
#增加指定的Handler
logger.addHandler(handler)
logger.addHandler(console)


print("""
------- Luffy Bank ---------
1. 賬戶信息
2. 提現
""")
# data = {‘balance‘: 100, ‘credit‘: 50}
# with open(file_path1, ‘w‘, encoding=‘utf-8‘) as f:
#     json.dump(data,f)
user_status = False
def login(fun):
    def inner(*args,**kwargs):
        user_name = xiao
        pass_word = 123
        global user_status
        if user_status == False:
            username = input(user:>).strip()
            password = input(password:>).strip()
            if username == user_name and pass_word == password:
                logger.info(----登錄-----)
                print(welcome login...)
                user_status = True
            else:
                print(wrong username or passerword)
        if user_status == True:
            return fun(*args,**kwargs)
    return inner

@login
def transfer():
    tesla_balance = 75
    balance[balance] = balance[balance] - tesla_balance * 0.05 - 75

    print(f"購買tesla共花費{tesla_balance * 0.05 + 75},tesla賬戶增加{tesla_balance}")
    with open(file_path2, w, encoding=utf-8) as f2:
        json.dump(tesla_balance, f2)
    with open(file_path1, w, encoding=utf-8) as f3:
        json.dump(balance, f3)
@login
def withdraw():
    withdraw_money = int(input(請輸入提現金額:).strip())
    if withdraw_money > balance[credit]:
        print(f"提現金額超過信用額度:{balance[‘credit‘]}萬,請重新輸入")
    else:
        balance[balance] = balance[balance] - withdraw_money - withdraw_money*0.05
        print(f"剩下余額{ balance[‘balance‘]}")
    with open(file_path1, w, encoding=utf-8) as f2:
       json.dump(balance, f2)


while True:

    choice = input("""
請選擇如下序號:
1. 賬戶信息
2. 提現
3.轉賬
q.退出
>
""")
    #  此題前提在luffy 下存入data字典信息
    # data = {‘balance‘: 100, ‘credit‘: 50}
    with open(file_path1, r, encoding=utf-8) as f:
        # json.dump(data,f)
        balance = json.load(f)
    if choice == 1:
        logger.info(----顯示賬戶信息-----)
        print(f"當前余額:{balance[‘balance‘]}萬,信用額度:{balance[‘credit‘]}萬")
        continue

    if choice == 2:
        logger.info(----提現-----)
        print()
        withdraw()
        continue

    if choice == 3:
        logger.info(----轉賬-----)
        transfer()
        continue
    elif choice == q:
        exit()

python 常用模塊練習題&總結