-1

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

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.mimieText我已使用和包含在脚本电子邮件中multipart。但是输出不再只显示代码的相对变量。

    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

4 回答 4

2

在 python"""引号中的意思是从字面上理解它们之间的一切。

这里最简单的解决方案是定义一个 string myString="",然后在每个 print 语句,而不是打印,你可以附加到你的字符串myString=myString+"whatever I want to append\n"

于 2013-08-30T13:59:45.920 回答
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
于 2013-08-30T14:03:27.873 回答
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

您还可以进行字符串格式化

body = "Motion Detection Started\nPixel Threshold (How much) = {}\nSensitivity (changed Pixels) = {}\nFile Path for Image Save = {}".format(threshold, sensitivity, filepath)
于 2013-08-30T14:07:06.147 回答
0

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

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

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

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())
于 2013-08-30T15:10:43.973 回答