Python是一種流行的編程語言,它被廣泛應用於數據處理、機器學習、Web開發等領域。在命令行下,我們可以使用Python來創建各種實用工具,簡化我們的日常工作。本文將介紹如何使用Python實現簡單的命令行工具。
一、讀取命令行參數
在編寫命令行工具時,我們通常需要讀取命令行參數。Python提供了一個標準庫`argparse`來處理命令行參數。下面是一個簡單的示例,從命令行讀取兩個參數,並將它們相加:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('a', type=int, help='the first number')
parser.add_argument('b', type=int, help='the second number')
args = parser.parse_args()
result = args.a + args.b
print(result)
運行以上代碼,示例輸出如下:
$ python add.py 2 3 5
在命令行中輸入`python add.py 2 3`,程序將讀取兩個整數2和3,並將它們相加輸出結果5。
二、解析CSV文件
CSV(Comma-Separated Values)即逗號分隔值,是一種常用的數據格式。在Python中,我們可以使用標準庫`csv`來讀取和寫入CSV文件。下面是一個示例,讀取一個CSV文件並計算其中一列的和:
import csv
total_sales = 0
with open('sales.csv') as file:
reader = csv.reader(file)
for row in reader:
total_sales += float(row[1])
print(total_sales)
在上面的代碼中,我們打開一個名為`sales.csv`的文件,在循環中逐行讀取每個行,並將第二列的數字加入總銷售額中。
三、使用正則表達式
正則表達式是一種強大的文本處理工具,可用於匹配、搜索和替換字元串。Python內置了標準庫`re`來處理正則表達式。下面是一個示例,從HTML文本中提取所有鏈接:
import re
html = '<html><body><p>Website: <a href="http://example.com">http://example.com</a></p></body></html>'
pattern = re.compile('<a.*?href="(.*?)".*?>(.*?)</a>')
links = pattern.findall(html)
for link, text in links:
print('Link: ', link)
print('Text: ', text)
在上面的代碼中,我們使用正則表達式`<a.*?href=”(.*?)”.*?>(.*?)</a>`匹配URL和鏈接文本。然後,我們使用`findall`方法以元組列表的形式返回所有匹配項。最後,我們遍歷列表並列印每個鏈接和相應的文本。
四、生成隨機數
Python提供了一個`random`模塊,可以生成各種類型的隨機數。下面是一個示例,生成一個10個元素的隨機數列並對其進行排序:
import random
numbers = [random.randint(0, 100) for _ in range(10)]
print('Random numbers:', numbers)
numbers.sort()
print('Sorted numbers:', numbers)
在上面的代碼中,我們使用列表推導式生成10個隨機整數,其中每個元素都在0和100之間。然後,我們使用`sort`方法對列表進行升序排序,並列印排序後的結果。
五、發送郵件
Python內置了`smtplib`模塊,可用於發送電子郵件。下面是一個示例,發送一封包含文本和附件的電子郵件:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 郵件配置
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'user@example.com'
smtp_password = 'password'
# 構造郵件
msg = MIMEMultipart()
msg['From'] = smtp_username
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Test Email'
body = 'This is a test email.'
msg.attach(MIMEText(body, 'plain'))
with open('file.txt', 'rb') as file:
attachment = MIMEApplication(file.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename='file.txt')
msg.attach(attachment)
# 發送郵件
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(smtp_username, 'recipient@example.com', msg.as_string())
在上面的代碼中,我們首先配置SMTP伺服器和用戶名/密碼。然後,我們構造一個帶有文本和附件的電子郵件。最後,我們使用`SMTP`類連接到SMTP伺服器並發送電子郵件。
總結
在本文中,我們介紹了如何使用Python實現一些簡單的命令行工具,包括讀取命令行參數、解析CSV文件、使用正則表達式、生成隨機數和發送電子郵件。這些工具可以幫助我們完成各種常見任務,提高我們的工作效率。如果您感興趣,可以深入研究Python的標準庫和第三方庫,探索更多的可能性。
原創文章,作者:CJUF,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/136916.html
微信掃一掃
支付寶掃一掃