电竞比分网-中国电竞赛事及体育赛事平台

分享

用于自動化的 10 個殺手級 Python 腳本

 流形sbz 2023-11-25 發(fā)布于甘肅

用于自動化的 10 個殺手級 Python 腳本

您是否厭倦了在繁瑣的任務上浪費時間?

您是否夢想著一個計算機為您完成所有工作的世界?別無所求,因為我們有 5 個 Python 腳本,準備好告別體力勞動,自動化開始吧!

“自動化不是人類工人的敵人,而是盟友。自動化將工人從苦差事中解放出來,讓他有機會做更有創(chuàng)造力和更有價值的工作。

閱讀本文后,您將更好地了解許多類型的python腳本,您可以使用這些腳本來自動執(zhí)行日常無聊的任務。

Python是一種功能強大的語言,廣泛用于自動化各種任務。無論您是開發(fā)人員、系統(tǒng)管理員,還是只是想通過自動執(zhí)行日常任務來節(jié)省時間的人,Python 都能滿足您的需求。

1、文件傳輸腳本:

Python 中的文件傳輸腳本是一組用 Python 編程語言編寫的指令或程序,用于自動執(zhí)行通過網(wǎng)絡或在計算機之間傳輸文件的過程。

Python 提供了幾個可用于創(chuàng)建文件傳輸腳本的庫和模塊,例如套接字、ftplib、smtplib 和 paramiko 等。

下面是 Python 中一個簡單的文件傳輸腳本示例,該腳本使用套接字模塊通過網(wǎng)絡傳輸文件:

import socket

# create socket
s = socket.socket()

# bind socket to a address and port
s.bind(('localhost', 12345))

# put the socket into listening mode
s.listen(5)

print('Server listening...')

# forever loop to keep server running
while True:
    # establish connection with client
    client, addr = s.accept()
    print(f'Got connection from {addr}')

    # receive the file name
    file_name = client.recv(1024).decode()

    try:
        # open the file for reading in binary
        with open(file_name, 'rb') as file:
            # read the file in chunks
            while True:
                chunk = file.read(1024)
                if not chunk:
                    break
                # send the chunk to the client
                client.sendall(chunk)

        print(f'File {file_name} sent successfully')
    except FileNotFoundError:
        # if file not found, send appropriate message
        client.sendall(b'File not found')
        print(f'File {file_name} not found')

    # close the client connection
    client.close()

此腳本運行一個服務器,該服務器偵聽地址 localhost 和端口 12345 上的傳入連接。當客戶端連接時,服務器從客戶端接收文件名,然后讀取文件的內(nèi)容并將其以塊的形式發(fā)送到客戶端。如果未找到該文件,服務器將向客戶端發(fā)送相應的消息。

如上所述,還有其他庫和模塊可用于在python中創(chuàng)建文件傳輸腳本,例如使用ftp協(xié)議連接和傳輸文件的ftplib和用于SFTP(SSH文件傳輸協(xié)議)傳輸?shù)膒aramiko。 可以定制腳本以匹配特定要求或方案。

2、系統(tǒng)監(jiān)控腳本:

系統(tǒng)監(jiān)視腳本是一種 Python 腳本,用于監(jiān)視計算機或網(wǎng)絡的性能和狀態(tài)。該腳本可用于跟蹤各種指標,例如 CPU 使用率、內(nèi)存使用率、磁盤空間、網(wǎng)絡流量和系統(tǒng)正常運行時間。該腳本還可用于監(jiān)視某些事件或條件,例如錯誤的發(fā)生或特定服務的可用性。例如:

import psutil

# Get the current CPU usage
cpu_usage = psutil.cpu_percent()

# Get the current memory usage
memory_usage = psutil.virtual_memory().percent

# Get the current disk usage
disk_usage = psutil.disk_usage('/').percent

# Get the network activity
# Get the current input/output data rates for each network interface
io_counters = psutil.net_io_counters(pernic=True)
for interface, counters in io_counters.items():
    print(f'Interface {interface}:')
    print(f'  bytes sent: {counters.bytes_sent}')
    print(f'  bytes received: {counters.bytes_recv}')

# Get a list of active connections
connections = psutil.net_connections()
for connection in connections:
    print(f'{connection.laddr} <-> {connection.raddr} ({connection.status})')

# Print the collected data
print(f'CPU usage: {cpu_usage}%')
print(f'Memory usage: {memory_usage}%')
print(f'Disk usage: {disk_usage}%')

此腳本使用 psutil 模塊中的cpu_percent、virtual_memory和disk_usage函數(shù)分別檢索當前 CPU 使用率、內(nèi)存使用率和磁盤使用率。

virtual_memory 函數(shù)返回具有各種屬性的對象,例如內(nèi)存總量以及已用內(nèi)存量和可用內(nèi)存量。

disk_usage 函數(shù)將路徑作為參數(shù),并返回具有磁盤上總空間量以及已用空間量和可用空間量等屬性的對象。

3、網(wǎng)頁抓取腳本,最常用: 此腳本可用于從網(wǎng)站中提取數(shù)據(jù)并以結(jié)構(gòu)化格式(如電子表格或數(shù)據(jù)庫)存儲數(shù)據(jù)。這對于收集數(shù)據(jù)進行分析或跟蹤網(wǎng)站上的更改非常有用。例如:

import requests
from bs4 import BeautifulSoup

# Fetch a web page
page = requests.get('http://www.')

# Parse the HTML content
soup = BeautifulSoup(page.content, 'html.parser')

# Find all the links on the page
links = soup.find_all('a')

# Print the links
for link in links:
    print(link.get('href'))

在這里,您可以看到美麗湯包裝的強大功能。您可以使用此包找到任何類型的 dom 對象,因為我已經(jīng)展示了如何找到頁面上的所有鏈接。

您可以修改腳本以抓取其他類型的數(shù)據(jù),或?qū)Ш降秸军c的不同頁面。還可以使用 find 方法查找特定元素,或使用帶有其他參數(shù)的 find_all 方法來篩選結(jié)果。

4、電子郵件自動化腳本:

此腳本可用于根據(jù)特定條件自動發(fā)送電子郵件。例如,您可以使用此腳本向團隊發(fā)送每日報告,或者在重要截止日期臨近時向自己發(fā)送提醒。下面是如何使用 Python 發(fā)送電子郵件的示例:

import smtplib
from email.mime.text import MIMEText

# Set the SMTP server and login credentials
smtp_server = 'smtp.gmail.com'
smtp_port = 587
username = 'your@email.com'
password = 'yourpassword'

# Set the email parameters
recipient = 'recipient@email.com'
subject = 'Test email from Python'
body = 'This is a test email sent from Python.'

# Create the email message
msg = MIMEText(body)
msg['Subject'] = subject
msg['To'] = recipient
msg['From'] = username

# Send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.send_message(msg)
server.quit()

此腳本使用 smtplib 和電子郵件模塊通過簡單郵件傳輸協(xié)議 SMTP 發(fā)送電子郵件。

來自smtplib模塊的SMTP類用于創(chuàng)建SMTP客戶端,starttls和登錄方法用于建立安全連接,電子郵件模塊中的MIMEText類用于創(chuàng)建多用途Internet郵件擴展MIME格式的電子郵件。

MIMEText 構(gòu)造函數(shù)將電子郵件的正文作為參數(shù),您可以使用 setitem 方法來設置電子郵件的主題、收件人和發(fā)件人。

創(chuàng)建電子郵件后,SMTP 對象的send_message方法將用于發(fā)送電子郵件。然后調(diào)用 quit 方法以關(guān)閉與 SMTP 服務器的連接。

5、密碼管理器腳本:

密碼管理器腳本是一種用于安全存儲和管理密碼的 Python 腳本。該腳本通常包括用于生成隨機密碼、將哈希密碼存儲在安全位置(如數(shù)據(jù)庫或文件)以及在需要時檢索密碼的函數(shù)。

import secrets
import string

# Generate a random password
def generate_password(length=16):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(secrets.choice(characters) for i in range(length))
    return password

# Store a password in a secure way
def store_password(service, username, password):
    # Use a secure hashing function to store the password
    hashed_password = hash_function(password)

    # Store the hashed password in a database or file
    with open('password_database.txt''a') as f:
        f.write(f'{service},{username},{hashed_password}\n')

# Retrieve a password
def get_password(service, username):
    # Look up the hashed password in the database or file
    with open('password_database.txt') as f:
        for line in f:
            service_, username_, hashed_password_ = line.strip().split(',')
            if service == service_ and username == username_:
                # Use a secure hashing function to compare the stored password with the provided password
                if hash_function(password) == hashed_password_:
                    return password
        return None

上述示例腳本中的 generate_password 函數(shù)使用字母、數(shù)字和標點字符的組合生成指定長度的隨機密碼。

store_password函數(shù)將服務,如網(wǎng)站或應用程序、用戶名和密碼作為輸入,并將散列密碼存儲在安全位置。

get_password函數(shù)將服務和用戶名作為輸入,如果在安全存儲位置找到相應的密碼,則檢索相應的密碼。

自動化的 Python 腳本的第 2 部分

歡迎回來!

在上一篇文章中,我們深入研究了 Python 腳本的世界,我們還沒有揭開Python腳本的所有奧秘。

在本期中,我們將發(fā)現(xiàn)其余五種類型的腳本,這些腳本將讓您立即像專業(yè)人士一樣編碼。

6、自動化數(shù)據(jù)分析:

Python的pandas是數(shù)據(jù)分析和操作的強大工具。以下腳本演示如何使用它自動執(zhí)行清理、轉(zhuǎn)換和分析數(shù)據(jù)集的過程。

import pandas as pd

# Reading a CSV file
df = pd.read_csv('data.csv')

# Cleaning data
df.dropna(inplace=True) # Dropping missing values
df = df[df['column_name'] != 'some_value'# Removing specific rows

# Transforming data
df['column_name'] = df['column_name'].str.lower() # Changing string to lowercase
df['column_name'] = df['column_name'].astype(int) # Changing column datatype

# Analyzing data
print(df['column_name'].value_counts()) # Prints the frequency of unique values in the column

# Saving the cleaned and transformed data to a new CSV file
df.to_csv('cleaned_data.csv', index=False)

上面腳本中的注釋對于具有 python 基礎(chǔ)知識的人來說非常簡單。

該腳本是一個簡單的示例,用于演示 pandas 庫的強大功能以及如何使用它來自動執(zhí)行數(shù)據(jù)清理、轉(zhuǎn)換和分析任務。

但是,腳本是有限的,在實際方案中,數(shù)據(jù)集可能要大得多,清理、轉(zhuǎn)換和分析操作可能會更復雜。

7、自動化計算機視覺任務: 自動化計算機視覺任務是指使用 Python 及其庫自動執(zhí)行各種圖像處理和計算機視覺操作。Python 中最受歡迎的計算機視覺任務庫之一是 opencv。

OpenCV是一個主要針對實時計算機視覺的編程函數(shù)庫。它提供了廣泛的功能,包括圖像和視頻 I/O、圖像處理、視頻分析、對象檢測和識別等等。例如:

import cv2

# Load the cascade classifier for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Load the image
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

# Draw rectangles around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

# Show the image

cv2.imshow('Faces', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

上面的腳本檢測圖像中的人臉。它首先加載一個級聯(lián)分類器用于人臉檢測,這個分類器是一個預先訓練的模型,可以識別圖像中的人臉。

然后它加載圖像并使用 cv2.cvtColor()方法將其轉(zhuǎn)換為灰度。然后將圖像傳遞給分類器的 detectMultiScale()方法,該方法檢測圖像中的人臉。該方法返回檢測到的人臉的坐標列表。

然后,該腳本循環(huán)遍歷坐標列表,并使用 cv2.rectangle()方法在檢測到的人臉周圍繪制矩形。最后,使用 cv2.imshow()方法在屏幕上顯示圖像。

這只是OpenCV可以實現(xiàn)的目標的一個基本示例,還有更多可以自動化的功能,例如對象檢測,圖像處理和視頻分析。OpenCV 是一個非常強大的庫,可用于自動執(zhí)行各種計算機視覺任務,例如面部識別、對象跟蹤和圖像穩(wěn)定。

8、自動化數(shù)據(jù)加密:

自動化數(shù)據(jù)加密是指使用 Python 及其庫自動加密和解密數(shù)據(jù)和文件。

Python 中最受歡迎的數(shù)據(jù)加密庫之一是密碼學。

“密碼學”是一個提供加密配方和原語的庫。它包括高級配方和常見加密算法(如對稱密碼、消息摘要和密鑰派生函數(shù))的低級接口。以下示例演示了如何使用加密庫加密文件:

import os
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

password = b'super_secret_password'
salt = os.urandom(16)
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256,
    iterations=100000,
    length=32,
    salt=salt,
    backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(password))
cipher = Fernet(key)

# Encrypt the file
with open('file.txt''rb') as f:
    data = f.read()

cipher_text = cipher.encrypt(data)

with open('file.txt''wb') as f:
    f.write(cipher_text)

它首先使用 PBKDF2HMAC 密鑰派生函數(shù)生成密鑰,這是一個基于密碼的密鑰派生函數(shù),使用安全哈希算法 SHA-256salt值。

salt 值是使用os.urandom()函數(shù)生成的,該函數(shù)生成加密安全的隨機字節(jié)。

然后,它創(chuàng)建一個 Fernet 對象,該對象是對稱(也稱為“密鑰”)身份驗證加密的實現(xiàn)。

然后,它讀取明文文件,并使用 Fernet 對象的encrypt()方法對其進行加密。最后,它將加密數(shù)據(jù)寫入文件。

請務必注意,用于加密文件的密鑰必須保密并安全存儲。如果密鑰丟失或泄露,加密的數(shù)據(jù)將無法讀取。

9、自動化測試和調(diào)試:

自動化測試和調(diào)試是指使用 Python 及其庫自動運行測試和調(diào)試代碼。在 Python 中,有幾個流行的庫用于自動化測試和調(diào)試,例如 unittest、pytest、nose 和 doctest。

下面是使用 unittest 庫自動測試在給定字符串中查找最長回文子字符串的 Python 函數(shù)的示例:

def longest_palindrome(s):
    n = len(s)
    ans = ''
    for i in range(n):
        for j in range(i+1, n+1):
            substring = s[i:j]
            if substring == substring[::-1] and len(substring) > len(ans):
                ans = substring
    return ans

class TestLongestPalindrome(unittest.TestCase):
    def test_longest_palindrome(self):
        self.assertEqual(longest_palindrome('babad'), 'bab')
        self.assertEqual(longest_palindrome('cbbd'), 'bb')
        self.assertEqual(longest_palindrome('a'), 'a')
        self.assertEqual(longest_palindrome(''), '')

if __name__ == '__main__':
    unittest.main()

此腳本使用 unittest 庫自動測試在給定字符串中查找最長回文子字符串的 Python 函數(shù)。

'longest_palindrome' 函數(shù)將字符串作為輸入,并通過遍歷所有可能的子字符串并檢查它是否是回文并且它的長度大于前一個來返回最長的回文子字符串。

該腳本還定義了一個從 unittest 繼承的“TestLongestPalindrome”類。測試用例,并包含多種測試方法。

每個測試方法都使用 assertEqual()方法來檢查 longest_palindrome() 函數(shù)的輸出是否等于預期的輸出。

當腳本運行時,將調(diào)用 unittest.main()函數(shù),該函數(shù)運行 TestLongestPalindrome類中的所有測試方法。

如果任何測試失敗,即longest_palindrome()函數(shù)的輸出不等于預期輸出,則會打印一條錯誤消息,指示哪個測試失敗以及預期和實際輸出是什么。

此腳本是如何使用 unittest 庫自動測試 Python 函數(shù)的示例。它允許您在將代碼部署到生產(chǎn)環(huán)境之前輕松測試代碼并捕獲任何錯誤或錯誤。

10、自動化時間序列預測:

自動化時間序列預測是指使用 Python 及其庫自動預測時間序列數(shù)據(jù)的未來值。在Python中,有幾個流行的庫可以自動化時間序列預測,例如statsmodels和prophet。

“prophet”是由Facebook開發(fā)的開源庫,它提供了一種簡單快捷的方式來執(zhí)行時間序列預測。

它基于加法模型,其中非線性趨勢與每年、每周和每天的季節(jié)性以及假日效應相吻合。它最適合具有強烈季節(jié)性影響的時間序列和多個季節(jié)的歷史數(shù)據(jù)。

下面是使用 prophet 庫對每日銷售數(shù)據(jù)執(zhí)行時間序列預測的示例:

import pandas as pd
from fbprophet import Prophet

# Read in data
df = pd.read_csv('sales_data.csv')

# Create prophet model
model = Prophet()

# Fit model to data
model.fit(df)

# Create future dataframe
future_data = model.make_future_dataframe(periods=365)

# Make predictions
forecast = model.predict(future_data)

# Print forecast dataframe
print(forecast[['ds''yhat''yhat_lower''yhat_upper']])

正如Mr.X所說:一張圖片勝過千言萬語

還可以通過在上面添加以下代碼行來包含預測銷售額的視覺對象:

# Import visualization library
import matplotlib.pyplot as plt

# Plot predicted values
model.plot(forecast)
plt.show()

# Plot predicted values with uncertainty intervals
model.plot(forecast)
plt.fill_between(forecast['ds'], forecast['yhat_lower'], forecast['yhat_upper'], color='pink')
plt.show()

# Plot component of the forecast
model.plot_components(forecast)
plt.show()

第一個可視化效果

model.plot(forecast)

顯示預測值和歷史數(shù)據(jù),它可以讓您大致了解模型擬合數(shù)據(jù)的程度。

第二個可視化效果:

plt.fill_between(預測['ds'],預測['yhat_lower'],預測['yhat_upper'],color='pink'

顯示具有不確定性區(qū)間的預測值,這使您可以查看預測中有多少不確定性。

第三個可視化效果

model.plot_components(forecast)

顯示預測的組成部分,例如趨勢、季節(jié)性和節(jié)假日。

結(jié)論

總之,Python的自動化能力超強并且不斷發(fā)展,每天都在開發(fā)新的庫和框架。

使用諸如pandas,opencv,cryptography,unittest,prophet等庫,使得以高效和自動化的方式執(zhí)行這些任務變得更加容易。

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多