python how to debug errors by logging issues
<p>I'm very new to python and have a script that runs when an email is sent to the server. My issue is trying to debug the script. How can I push any errors to a log file?</p>

<p>Here is the script:</p>

<pre><code>#!/usr/bin/python
import sys, email

email_input = email.message_from_string(sys.stdin.read())
directory = "/home/someuser/files"


counter = 1
for part in email_input.walk():
    # multipart/* are just containers
    if part.get_content_maintype() == 'multipart':
        continue
    # Applications should really sanitize the given filename so that an
    # email message can't be used to overwrite important files
    filename = part.get_filename()
    if not filename:
        ext = mimetypes.guess_extension(part.get_content_type())
        if not ext:
            # Use a generic bag-of-bits extension
            ext = '.bin'
        filename = 'part-%03d%s' % (counter, ext)
    counter += 1
    fp = open(os.path.join(directory, filename), 'wb')
    fp.write(part.get_payload(decode=True))
    fp.close()
</code></pre>

<p>There are at least a couple ways to do this:</p>

<ol>
<li><p>You can print to stdout and redirect to a file.  Here is an example</p>

<p>â  ~ python print_this.py &amp;> log.txt</p>

<p>â  ~ cat log.txt </p>

<p>this message</p>

<p>â  ~ cat print_this.py </p>

<p>print("this message")</p></li>
<li><p>You can use the logging library and attach a file handler:</p></li>
</ol>

<p><a href="https://docs.python.org/2/library/logging.handlers.html#filehandler" rel="nofollow">https://docs.python.org/2/library/logging.handlers.html#filehandler</a></p>

<p>This is slightly complicated.  But you can see an example of some code I wrote here where you can see where to put the handler:  </p>

<p><a href="https://github.com/nogibjj/sensible/blob/master/sensible/loginit.py" rel="nofollow">https://github.com/nogibjj/sensible/blob/master/sensible/loginit.py</a></p>

<p>How to Add This As An Example Using Print:</p>

<pre><code>import sys, email

email_input = email.message_from_string(sys.stdin.read())
directory = "/home/someuser/files"


counter = 1
for part in email_input.walk():
    # multipart/* are just containers
    if part.get_content_maintype() == 'multipart':
        print("part: %s Found multipart" % part)
        continue
    # Applications should really sanitize the given filename so that an
    # email message can't be used to overwrite important files
    filename = part.get_filename()
    if not filename:
        ext = mimetypes.guess_extension(part.get_content_type())
        if not ext:
            # Use a generic bag-of-bits extension
            ext = '.bin'
        filename = 'part-%03d%s' % (counter, ext)
    counter += 1
    fp = open(os.path.join(directory, filename), 'wb')
    fp.write(part.get_payload(decode=True))
    fp.close()
</code></pre>

python