好了,开始看代码。我标红了需要输出中文要加的代码,如果您是英文系统,就不用加这几行了。

#!/usr/bin/env python
import datetime #导入日期时间库
import subprocess
import reportlab.pdfbase.ttfonts #导入reportlab的注册字体
reportlab.pdfbase.pdfmetrics.registerFont(reportlab.pdfbase.ttfonts.TTFont('song', '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc')) #注册字体
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch #导入单位英寸

def disk_report():
p = subprocess.Popen("df -h ",shell=True,stdout=subprocess.PIPE)
return p.stdout.readlines() #看不懂的前面有讲解,返回行列表。
 
def create_pdf(input,output="diskfree.pdf"):
now = datetime.datetime.today()
date = now.strftime("%h %d %Y %H:%M:%S") #设定日期格式
c = canvas.Canvas(output)
c.setFont('song',10) #设置字体字号
textobject = c.beginText() #定义开始
textobject.setTextOrigin(inch,11*inch) #定义位置
textobject.textLines('''Disk Capacity Report: %s ''' % date ) #输出标题
for line in input: #通过循环的方式一行一行写入文件
line=line.decode("utf8") #转换line变量为 utf8 格式
textobject.textLine(line.strip()) #写入文件
c.drawText(textobject)
c.showPage()
c.save()
report = disk_report()
create_pdf(report)

执行结果是: