日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

用于自動(dòng)化的 10 個(gè)殺手級(jí) Python 腳本

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

用于自動(dòng)化的 10 個(gè)殺手級(jí) Python 腳本

您是否厭倦了在繁瑣的任務(wù)上浪費(fèi)時(shí)間?

您是否夢(mèng)想著一個(gè)計(jì)算機(jī)為您完成所有工作的世界?別無(wú)所求,因?yàn)槲覀冇?5 個(gè) Python 腳本,準(zhǔn)備好告別體力勞動(dòng),自動(dòng)化開始吧!

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

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

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

1、文件傳輸腳本:

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

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

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

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()

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

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

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

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

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ù)分別檢索當(dāng)前 CPU 使用率、內(nèi)存使用率和磁盤使用率。

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

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

3、網(wǎng)頁(yè)抓取腳本,最常用: 此腳本可用于從網(wǎng)站中提取數(shù)據(jù)并以結(jié)構(gòu)化格式(如電子表格或數(shù)據(jù)庫(kù))存儲(chǔ)數(shù)據(jù)。這對(duì)于收集數(shù)據(jù)進(jìn)行分析或跟蹤網(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'))

在這里,您可以看到美麗湯包裝的強(qiáng)大功能。您可以使用此包找到任何類型的 dom 對(duì)象,因?yàn)槲乙呀?jīng)展示了如何找到頁(yè)面上的所有鏈接。

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

4、電子郵件自動(dòng)化腳本:

此腳本可用于根據(jù)特定條件自動(dòng)發(fā)送電子郵件。例如,您可以使用此腳本向團(tuán)隊(duì)發(fā)送每日?qǐng)?bào)告,或者在重要截止日期臨近時(shí)向自己發(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 和電子郵件模塊通過簡(jiǎn)單郵件傳輸協(xié)議 SMTP 發(fā)送電子郵件。

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

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

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

5、密碼管理器腳本:

密碼管理器腳本是一種用于安全存儲(chǔ)和管理密碼的 Python 腳本。該腳本通常包括用于生成隨機(jī)密碼、將哈希密碼存儲(chǔ)在安全位置(如數(shù)據(jù)庫(kù)或文件)以及在需要時(shí)檢索密碼的函數(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ù)字和標(biāo)點(diǎn)字符的組合生成指定長(zhǎng)度的隨機(jī)密碼。

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

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

自動(dòng)化的 Python 腳本的第 2 部分

歡迎回來(lái)!

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

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

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

Python的pandas是數(shù)據(jù)分析和操作的強(qiáng)大工具。以下腳本演示如何使用它自動(dòng)執(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)

上面腳本中的注釋對(duì)于具有 python 基礎(chǔ)知識(shí)的人來(lái)說非常簡(jiǎn)單。

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

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

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

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

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()

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

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

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

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

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

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

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

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

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ù)生成密鑰,這是一個(gè)基于密碼的密鑰派生函數(shù),使用安全哈希算法 SHA-256salt值。

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

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

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

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

9、自動(dòng)化測(cè)試和調(diào)試:

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

下面是使用 unittest 庫(kù)自動(dòng)測(cè)試在給定字符串中查找最長(zhǎng)回文子字符串的 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 庫(kù)自動(dòng)測(cè)試在給定字符串中查找最長(zhǎng)回文子字符串的 Python 函數(shù)。

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

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

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

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

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

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

10、自動(dòng)化時(shí)間序列預(yù)測(cè):

自動(dòng)化時(shí)間序列預(yù)測(cè)是指使用 Python 及其庫(kù)自動(dòng)預(yù)測(cè)時(shí)間序列數(shù)據(jù)的未來(lái)值。在Python中,有幾個(gè)流行的庫(kù)可以自動(dòng)化時(shí)間序列預(yù)測(cè),例如statsmodels和prophet。

“prophet”是由Facebook開發(fā)的開源庫(kù),它提供了一種簡(jiǎn)單快捷的方式來(lái)執(zhí)行時(shí)間序列預(yù)測(cè)。

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

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

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所說:一張圖片勝過千言萬(wàn)語(yǔ)

還可以通過在上面添加以下代碼行來(lái)包含預(yù)測(cè)銷售額的視覺對(duì)象:

# 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()

第一個(gè)可視化效果

model.plot(forecast)

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

第二個(gè)可視化效果:

plt.fill_between(預(yù)測(cè)['ds'],預(yù)測(cè)['yhat_lower'],預(yù)測(cè)['yhat_upper'],color='pink'

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

第三個(gè)可視化效果

model.plot_components(forecast)

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

結(jié)論

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

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

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

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多