2013-07-18 19 views
0

我對Python非常陌生,在使用Python-2.7.3之後,搜索並提出空白我想我會問社區。Python循環並將打印輸出追加到變量中用於發送電子郵件

我想基本上捕獲每個迭代到一個變量,所以我可以使用該變量作爲我的電子郵件的正文。我不想寫一個文件,然後用它作爲我的身體。

我已經沒有運氣嘗試這樣做:

for sourceFile in sortedSourceFiles: 
     print "Checking '%s' " % sourceFile += MsgBody 

這裏是我所得到的,當我運行它:

File "check_files_alert.py", line 76 
    print "Checking '%s' " % sourceFile += MsgBody 
             ^
SyntaxError: invalid syntax 

很抱歉的新手問題。
感謝

回答

1

的問題是不明確的。要麼捕獲標準輸出,要麼希望打印,然後追加或僅追加。我會回答所有三個。

如果你有一個打印功能,但你不想打印它,而是把它的打印輸出到列表中,那麼你想要做的就是捕獲stdout流。請參閱this question瞭解如何操作。

如果你要打印,然後追加,那麼你可以像這樣

for sourcefile in sortedsourcefiles: 
    MsgBody += sourceFile 
    print "Checking %s" % MsgBody 

東西,如果你只是想將其追加那麼這應該足夠了。

for sourcefile in sortedsourcefiles: 
    MsgBody += sourceFile 

希望這對我有所幫助。如果你有任何疑問問。

0

你會想這樣做:

for sourcefile in sortedsourcefiles: 
    MsgBody += sourceFile 
    print "Checking %s" % MsgBody 

你以前的代碼是把它變成一個字符串,然後嘗試添加到它。

0

我真的不知道你在這裏試圖做什麼。如果你想保留一個變量,你爲什麼使用print

如果你只是想連接在MsgBody行,你應該這樣做:

for sourceFile in sortedSourceFiles: 
    MsgBody += "Checking '%s' \n" % sourceFile 

甚至更​​好:

MsgBody = '\n'.join("Checking '%s'" % sourceFile for sourceFile in sortedSourceFiles) 
0
for sourceFile in sortedSourceFiles: 
    MsgBody += sourceFile 
相關問題