Python是一种功能强大的编程语言,它可以帮助我们解决日常生活中的各种问题。下面是一些使用Python解决生活问题的例子:
自动化邮件发送
如果你需要定期发送邮件,可以使用Python编写脚本自动化这一过程。以下是一个简单的示例代码,用于发送邮件:
```python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_email(subject, content, to_addr):
smtp_server = 'smtp.example.com'
from_addr = ''
password = 'your_password'
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = Header(subject, 'utf-8')
server = smtplib.SMTP(smtp_server, 25)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
调用函数发送邮件
send_email('Test Subject', 'Test Content', '')
计算出租车费用
出租车费用通常是根据行驶的公里数和等待时间来计算的。以下是一个使用Python进行出租车费用计算的示例:
```python
km = float(input('请输入行进的公里: '))
wait = float(input('请输入等待时间长度(秒): '))
if 4.0 <= km <= 24.0:
price = (10.0 + int((km - 4.0) / 0.5)) * 1.5
if wait >= 200:
price += int(wait / 200)
print('应付金额: %.2f' % price)
多参数功能
Python允许在函数调用中传递无限数量的参数,这为编写灵活的程序提供了便利。
```python
def test(*arg):
print(arg)
test(1, 3, 60, 23, 435)
自动删除备份文件
如果你经常需要清理自动生成的备份文件,可以编写一个Python脚本来帮助你完成这项任务。
```python
from os.path import walk, join, normpath
from os import chdir, remove
def scan(arg, dirname):
for root, dirs, files in walk(dirname):
for file in files:
if file.endswith('.bak'): 假设备份文件以.bak结尾
filepath = join(root, file)
try:
remove(filepath)
print('已删除文件:', filepath)
except OSError as e:
print('删除文件时出错:', e)
调用函数扫描D盘下的所有目录并删除.bak文件
scan('.', 'D:\\')
异常处理
在编写程序时,异常处理是非常重要的,它可以帮助我们更好地处理错误情况。
```python
def check_args(args):
if not args.host:
msg = 'Args missing! One of the following args should be specified \n--host 192.168.1.1 \n-f TargetFile \n'
raise Exception(msg)
示例用法
parser = argparse.ArgumentParser()
parser.add_argument('--host', type=str, help='IP address')
parser.add_argument('-f', '--file', type=str, help='Target file')
args = parser.parse_args()
check_args(args)
列表转字符串
有时候我们需要将命令行传入的列表参数转换为字符串格式。
```python
host_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
host_str = ' '.join(host_list)
client.connect((host_str, args.p))
使用argparse函数
argparse是Python的一个标准库,用于编写用户友好的命令行接口。