Python打印输出到电子邮件

时间:2013-08-30 13:54:25

标签: python

我有一个脚本可以完美地打印变量(由用户设置)。

os.system('clear')

print "Motion Detection Started"
print "------------------------"
print "Pixel Threshold (How much)   = " + str(threshold)
print "Sensitivity (changed Pixels) = " + str(sensitivity)
print "File Path for Image Save     = " + filepath
print "---------- Motion Capture File Activity --------------" 

我现在希望通过电子邮件将此代码发送给自己以确认运行时间。我已使用email.mimieTextmultipart在脚本邮件中添加了该邮件。但输出不再仅仅显示代码的相对变量。

    body =  """ Motion Detection Started \n Pixel Threshold (How much)   = " + str(threshold) \n    Sensitivity (changed Pixels) = " + str(sensitivity) \n File Path for Image Save     = " + filepath """

我确定它是“”包装,但不清楚我应该使用什么呢?

4 个答案:

答案 0 :(得分:2)

in python """引用意味着从字面上理解它们之间的所有内容。

此处最简单的解决方案是定义字符串myString="",然后在每个打印语句中,您可以使用myString=myString+"whatever I want to append\n"附加到字符串而不是打印

答案 1 :(得分:1)

应该是:

body =  " Motion Detection Started \n Pixel Threshold (How much)   = " + str(threshold) + \
        "\n Sensitivity (changed Pixels) = " + str(sensitivity) + \
        "\n File Path for Image Save     = " + filepath

答案 2 :(得分:1)

当你执行以下操作时,你告诉它所有字符串的一部分(请注意代码如何突出显示):

body =  """ Motion Detection Started \n Pixel Threshold (How much)   = " + str(threshold) \n    Sensitivity (changed Pixels) = " + str(sensitivity) \n File Path for Image Save     = " + filepath """

您需要将变量实际添加到字符串中,就像在print语句中连接它们一样。

body =  "Motion Detection Started \n Pixel Threshold (How much)   = " + str(threshold) + " \n    Sensitivity (changed Pixels) = " + str(sensitivity) + "\n File Path for Image Save     = " + filepath

你也可以string formatting

body = "Motion Detection Started\nPixel Threshold (How much) = {}\nSensitivity (changed Pixels) = {}\nFile Path for Image Save = {}".format(threshold, sensitivity, filepath)

答案 3 :(得分:0)

如果您希望电子邮件代码更具可重用性和强大功能, Template strings 可能会对您有所帮助。例如,将电子邮件文本作为模板保存在单独的文件template.txt

Motion Detection Started
------------------------------------------------------
Pixel Threshold (How much)   =  $threshold
Sensitivity (changed Pixels) =  $sensitivity
File Path for Image Save     =  $filepath
---------- Motion Capture File Activity --------------

并在您的代码中创建一个类,用于与一个或多个类实例一起发送电子邮件(您可以拥有多个模板):

import string

class DebugEmail():    
    def __init__(self, templateFileName="default_template.txt"):
        with open(templateFileName) as f:
            self.template = string.Template(f.read())

    def send(self, data):
        body = self.template.safe_substitute(data)
        print(body) # replace by sending email

debugEmail1 = DebugEmail("template.txt")

# and test it like this:

threshold = 1
sensitivity = 1
debugEmail1.send(locals())

sensitivity = 200
filepath = "file"
debugEmail1.send(locals())