Mosh Python 学习笔记 9-2 Python Standard Library
9.9 Working with Timestamps
timestamps的用法如下:
# get the current system time
time.time()
9.10 Working with DateTimes
datetime的用法如下:
from datetime import datetime
import time
datetime(2022, 1, 1)
# to parse the string into datetime object
datetime.strptime("2022/01/01", "%Y/%m/%d")
# convert timestamp into datetime
dt = datetime.fromtimestamp(time.time())
dt.year
dt.month
# from datetime object into string
dt.strftime()
9.11 Working with Time Deltas
timedelta deals with time durations. for example, the ‘duration’ below is a timedelta object:
from datetime import datetime, timedelta
dt1 = datetime(2022, 1, 1)
dt2 = datetime.now()
duration = dt2 - dt1
# .days attribute represents how many days in a timedelta
# object
duration.days
# .seconds attribute represents the rest seconds besides
# days
duration.seconds
# total_seconds() converts the time duration into seconds
duration.total_seconds()
one can also add timedelta object to a timestamp object, like
# add one day to 1st Jan, 2022
datetime(2022, 1, 1) + timedelta(1)
# add days and seconds
datetime(2022, 1, 1) + timedelta(days=1, seconds=1)
9.12 Generating Random Values
random用法如下:
import random
import string
# generate a random number between 0 and 1
print(random.random())
# generate a random number between 1 and 10
print(random.randint(1, 10))
# generate a random number in the array
print(random.choice([1, 2, 3, 4]))
# generate 2 random numbers in the array
print(random.choices([1, 2, 3, 4], k=2))
# generate 4 random charaters with given string
# string object has a join method which can join strings
# together
# the content in "" considered as seperator
# string.ascii_letters and string.digits can get all
# characters and numbers
print("".join(random.choices(string.ascii_letters + string.digits, k=4)))
# shuffle array
numbers = [1, 2, 3, 4]
random.shuffle(numbers)
9.13 Opening the Browser
用python打开一个网页的操作是:
import webbrowser
print("Develoyment completed")
webbrowser.open("http://baidu.com")
9.14 Sending Emails
使用python发送邮件的方法,以qq邮箱为例:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from pathlib import Path
import smtplib
# 配置message,需要注意的是from后面需要填写完整的发件邮箱
# message.attach()后是邮件的正文内容
# MIMEImage()可以在邮件中显示一张图片,但需注意它需要的是二进制的输入
message = MIMEMultipart()
message["from"] = "xxxxxxx@qq.com"
message["to"] = "xxxxxxxx@icloud.com"
message["subject"] = "For the learn of python"
message.attach(MIMEText("Body"))
message.attach(MIMEImage(Path("xxxx.png").read_bytes()))
# 真正在发送邮件时可能会出现各种error,需要raise特定的error
# qq邮箱465的port似乎不能连接,这里使用了qq邮箱给出的第二个
# smtp.ehlo()和smtp.startls()是smtp约定俗成的protocol
# smtp.login()要输入发件箱和qq邮箱给出的授权码,对于其他邮箱可能是密码即可
with smtplib.SMTP(host="smtp.qq.com", port=587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login("xxxxxxxxx@qq.com", "xxxxxxxxxxx")
smtp.send_message(message)
print("Sent...")
9.15 Templates
使用templates自动生成邮件内容:
- 在文件夹中创建template.html文件
- 在文件夹中写入template的内容,如:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
Hi <strong>$name</strong>, this is our test email.
</body>
</html>
$name为想要替换的内容
将<strong></strong>放在想要使其加粗的文字两侧
- 编辑主代码,以上一章节的代码内容为例,添加以下:
from pathlib import Path
from string import Template
# .substitute()可以接受dictionary也可以直接赋值,如
# name="John"
# 在body后注明template使用的是html
body = template.substitute({"name": "John"})
message.attach(MIMEText(body, "html"))
9.16 Command-line Arguments
在terminal输入以下代码可以给文件添加arguments
python app.py -a -b -c
可以利用argv给arguments赋值,例如:
import sys
# 每个文件至少有一个argument,即为文件名
if len(sys.argv) == 1:
print("USAGE: python3 app.py <password>")
else:
password = sys.argv[1]
print("Password", password)
如果没有添加过arguments,无法给其赋值
9.17 Running External Programs
使用python调取其他程序,假设程序other.py,调取方法如下:
import subprocess
# use capter_output_True to store the result in .stout
completed = subprocess.run(["python3", "other.py"],
capture_output=True,
text=True)
print(completed.stdout)