0

still a newbie in Python world so first question from me, hope somebody can help. So here's some simple code that lists the directories in a path and I'd like to send the output to an email. The email setup works as it'll mail the "TEXT" to me, but I have really struggled with trying to capture the stdout from the print function.

Thanks

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 = "me@me.com"
TO = ["me@me.com"]

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()
C9000
  • 3
  • 2
  • 1
    Don't immediately print the list of directories. Store it, e.g. in a list, then you can both print it and email it. – Duncan Jones Sep 01 '14 at 10:11
  • Thanks @Duncan - I did try this earlier by initialising a list and then appending the results of fulldir but I only ever got the last directory. – C9000 Sep 01 '14 at 10:45
  • Please show us the code where you tried that. Maybe we can help fix it. – Duncan Jones Sep 01 '14 at 10:46
  • Apologies @Duncan - it posted before I'd finished my comment. Code was simple mailDirs = [] before fulldir and then after fulldir mailDirs.append(fulldir) – C9000 Sep 01 '14 at 10:46
  • You'd need to declare that list outside all your for loops, otherwise you just overwrite it each time. I.e. it would be the first line in your example code. – Duncan Jones Sep 01 '14 at 10:47
  • Ahha great, that works but formatting isn't too pretty in mail as I get [thisdir, thatdir, otherdir]. Do you know if I can do a loop in the TEXT portion that'll format it a little better? – C9000 Sep 01 '14 at 10:59
  • @Duncan I've worked it out, can use TEXT = ("The following directories have been found:\n" + "\n".join(mailDirs)) - Thanks for help! – C9000 Sep 01 '14 at 11:27

1 Answers1

0

This code will join your list of directories with newlines, ensuring that one directory is listed on each line.

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)
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254