2014-09-01 73 views
0

仍然是Python世界的新手,所以我首先提出的問題,希望有人可以幫助。 因此,下面是一些簡單的代碼,列出了路徑中的目錄,並且我想將輸出發送到電子郵件。電子郵件設置的工作原理是它會將「TEXT」發送給我,但我非常努力地試圖從打印功能捕獲stdout。發送循環輸出到Python中的電子郵件

感謝

for root, dirs, files in os.walk(path): 
    for curDir in dirs: 
     fulldir = os.path.join(root, curDir) 
     print '\nThis dir : %s' % (fulldir) 

### Email setup 

SERVER = "myserver" 
PORT = "25" 

FROM = "[email protected]" 
TO = ["[email protected]"] 

SUBJECT = "Some dirs" 

TEXT = "The print loop from above please" 

# Prepare actual message 

message = """\ 
From: %s 
To: %s 
Subject: %s 

%s 
""" % (FROM, ", ".join(TO), SUBJECT, TEXT) 


### Send the message 
server = smtplib.SMTP(SERVER, PORT) 
server.sendmail(FROM, TO, message) 
server.quit() 
+1

不要立即打印目錄列表。存儲它,例如在列表中,然後您可以打印它並通過電子郵件發送。 – 2014-09-01 10:11:12

+0

Thanks @Duncan - 我之前通過初始化一個列表然後追加fulldir的結果嘗試了這一點,但我只有最後一個目錄。 – C9000 2014-09-01 10:45:13

+0

請向我們展示您嘗試過的代碼。也許我們可以幫助解決它。 – 2014-09-01 10:46:36

回答

0

該代碼會加入你用換行的目錄列表,確保一個目錄,每行上市。

import os 

path = "C:\\tmp" #my test path 

# See http://stackoverflow.com/q/973473/474189 for other alternatives 
dirs = [x[0] for x in os.walk(path) ] 

# Print if needed 
for d in dirs: 
    print "\nThis dir : %s" % (d)   

email_text = "\n".join(dirs)