自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

接口自動(dòng)化框架里常用的小工具

開發(fā)
在日常編程工作中,我們常常需要處理各種與時(shí)間、數(shù)據(jù)格式及配置文件相關(guān)的問題。本文整理了一系列實(shí)用的Python代碼片段,涵蓋了日期時(shí)間轉(zhuǎn)換、數(shù)據(jù)格式化與轉(zhuǎn)換、獲取文件注釋以及讀取配置文件等內(nèi)容,助力開發(fā)者提升工作效率,輕松應(yīng)對(duì)常見任務(wù)。

在日常編程工作中,我們常常需要處理各種與時(shí)間、數(shù)據(jù)格式及配置文件相關(guān)的問題。本文整理了一系列實(shí)用的Python代碼片段,涵蓋了日期時(shí)間轉(zhuǎn)換、數(shù)據(jù)格式化與轉(zhuǎn)換、獲取文件注釋以及讀取配置文件等內(nèi)容,助力開發(fā)者提升工作效率,輕松應(yīng)對(duì)常見任務(wù)。

1. 秒級(jí)與毫秒級(jí)時(shí)間戳獲取

# 獲取當(dāng)前秒級(jí)時(shí)間戳
def millisecond(add=0):
    return int(time.time()) + add
# 獲取當(dāng)前毫秒級(jí)時(shí)間戳
def millisecond_new():
    t = time.time()
    return int(round(t * 1000))

這兩個(gè)函數(shù)分別提供了獲取當(dāng)前時(shí)間的秒級(jí)和毫秒級(jí)時(shí)間戳的功能。millisecond()函數(shù)允許傳入一個(gè)可選參數(shù)add,用于增加指定的時(shí)間偏移量。

2. 當(dāng)前日期字符串獲取

#獲取當(dāng)前時(shí)間日期: 20211009
def getNowTime(tianshu=0):
shijian = int(time.strftime('%Y%m%d')) - tianshu
print(shijian)
return shijian

getNowTime()函數(shù)返回當(dāng)前日期(格式為YYYYMMDD),并支持傳入?yún)?shù)tianshu以減去指定天數(shù)。該函數(shù)適用于需要處理日期型數(shù)據(jù)且僅關(guān)注年月日的情況。

3.修復(fù)接口返回?zé)o引號(hào)JSON數(shù)據(jù)

def json_json():
    with open("源文件地址", "r") as f, open("目標(biāo)文件地址", "a+") as a:
        a.write("{")
        for line in f.readlines():
            if "[" in line.strip() or "{" in line.strip():
                formatted_line = "'" + line.strip().replace(":", "':").replace(" ", "") + ","
                print(formatted_line)  # 輸出修復(fù)后的行
                a.write(formatted_line + "\n")
            else:
                formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "',"
                print(formatted_line)  # 輸出修復(fù)后的行
                a.write(formatted_line + "\n")
        a.write("}")

此函數(shù)用于處理從接口復(fù)制的未正確格式化的JSON數(shù)據(jù),修復(fù)缺失的引號(hào),并將其寫入新的文件。源文件與目標(biāo)文件的路徑需替換為實(shí)際路徑。

4.將URL查詢字符串轉(zhuǎn)為JSON

from urllib.parse import urlsplit, parse_qs
def query_json(url):
    query = urlsplit(url).query
    params = dict(parse_qs(query))
    cleaned_params = {k: v[0] for k, v in params.items()}
    return cleaned_params

query_json()函數(shù)接收一個(gè)包含查詢字符串的URL,解析其查詢部分,將其轉(zhuǎn)換為字典形式,并清理多值參數(shù),只保留第一個(gè)值。

5.文件注釋提取

import os
def get_first_line_comments(directory, output_file):
    python_files = sorted([f for f in os.listdir(directory) if f.endswith('.py') and f != '__init__.py'])
    comments_and_files = []
    for file in python_files:
        filepath = os.path.join(directory, file)
        with open(filepath, 'r', encoding='utf-8') as f:
            first_line = f.readline().strip()
            if first_line.startswith('#'):
                comment = first_line[1:].strip()
                comments_and_files.append((file, comment))
    with open(output_file, 'w', encoding='utf-8') as out:
        for filename, comment in comments_and_files:
            out.write(f"{filename}: {comment}\n")
# 示例用法
get_first_line_comments('指定文件夾', '指定生成文件路徑.txt')
get_first_line_comments()函數(shù)遍歷指定目錄下的.py文件,提取每份文件的第
一行注釋(以#開頭),并將文件名與注釋對(duì)應(yīng)關(guān)系寫入指定的文本文件中。

6.讀取配置INI文件

import sys
import os
import configparser
class ReadConfig:
    def __init__(self, config_path):
        self.path = config_path
    def read_sqlConfig(self, fileName="sql.ini"):
        read_mysqlExecuteCon = configparser.ConfigParser()
        read_mysqlExecuteCon.read(os.path.join(self.path, fileName), encoding="utf-8")
        return read_mysqlExecuteCon._sections
    def read_hostsConfig(self, fileName="hosts.ini"):
        read_hostsCon = configparser.ConfigParser()
        read_hostsCon.read(os.path.join(self.path, fileName), encoding="utf-8")
        return read_hostsCon._sections
# 示例用法
config_reader = ReadConfig('配置文件所在路徑')
sql_config = config_reader.read_sqlConfig()
hosts_config = config_reader.read_hostsConfig()["hosts"]
ReadConfig類封裝了對(duì)INI配置文件的讀取操作,支持讀取sql.ini和hosts.ini文件。通過實(shí)例化該類并指定配置文件路徑,即可方便地獲取所需配置信息。

7.設(shè)置全局文件路徑

import os
def setFilePath(filePath):
    current_module_path = os.path.dirname(os.path.abspath(__file__))
    project_root_path = os.path.dirname(os.path.dirname(current_module_path))
    path = os.path.join(project_root_path, filePath.lstrip('/'))
    return os.path.abspath(path)
# 示例用法
confPath = setFilePath("地址文件路徑")

setFilePath()函數(shù)根據(jù)提供的相對(duì)路徑,結(jié)合當(dāng)前模塊的絕對(duì)路徑,計(jì)算出項(xiàng)目根目錄下的目標(biāo)文件或目錄的絕對(duì)路徑,便于在項(xiàng)目中統(tǒng)一管理資源位置。

責(zé)任編輯:華軒 來源: 測試開發(fā)學(xué)習(xí)交流
相關(guān)推薦

2012-03-15 10:32:05

Windows系統(tǒng)網(wǎng)絡(luò)故障

2022-08-29 10:11:28

PDFWord自動(dòng)化工具

2022-05-16 09:20:00

開發(fā)工具

2009-11-19 08:48:10

Windows 7桌面工具

2023-09-13 11:40:12

2024-04-30 15:05:36

Python接口自動(dòng)化

2024-02-28 16:04:04

深拷貝Python

2009-12-08 14:02:25

Windows 7小工

2010-07-01 10:24:30

UML小工具

2022-05-22 07:29:24

工具插件客戶端軟件

2013-03-29 14:46:33

App開發(fā)小工具輔助工具

2022-04-11 15:34:29

機(jī)器學(xué)習(xí)AutoML開源

2010-05-19 19:10:42

2011-03-10 09:03:35

Python

2021-05-10 11:06:31

Python工具代碼

2020-11-26 12:05:44

Python小工具代碼

2021-05-20 11:30:17

Python工具代碼

2021-11-05 06:57:50

架構(gòu)工具代碼

2011-04-12 12:53:17

2022-08-05 22:15:26

Python自動(dòng)化測試
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)