-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

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 に答える