Top-rated recipes tagged "main"http://code.activestate.com/recipes/tags/main/top/2011-07-14T20:42:35-07:00ActiveState Code Recipesentry_point decorator - no more if __name__ == '__main__' (Python) 2011-07-14T20:42:35-07:00yoav glaznerhttp://code.activestate.com/recipes/users/4178625/http://code.activestate.com/recipes/577791-entry_point-decorator-no-more-if-__name__-__main__/ <p style="color: grey"> Python recipe 577791 by <a href="/recipes/users/4178625/">yoav glazner</a> (<a href="/recipes/tags/main/">main</a>, <a href="/recipes/tags/python/">python</a>). Revision 2. </p> <p>Use this decorator to remove the UGLY "if __name__ == '__main__':"</p> Python script main line for graceful exception handling and logging (Python) 2010-09-11T05:46:59-07:00Trent Mickhttp://code.activestate.com/recipes/users/4173505/http://code.activestate.com/recipes/577258-python-script-main-line-for-graceful-exception-han/ <p style="color: grey"> Python recipe 577258 by <a href="/recipes/users/4173505/">Trent Mick</a> (<a href="/recipes/tags/error/">error</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/main/">main</a>, <a href="/recipes/tags/mainline/">mainline</a>, <a href="/recipes/tags/script/">script</a>). Revision 5. </p> <p>This is a recipe is often use for the mainline of my Python scripts. With this recipe your Python script will:</p> <ul> <li>gracefully handle <code>Ctrl+C</code> (i.e. <code>KeyboardInterrupt</code>)</li> <li>log an error (using the <code>logging</code> module) for uncaught exceptions, importantly <strong>with the file and line number</strong> in your Python code where the exception was raised</li> <li>gracefully ignore a closed output pipe (common when the user pipes your script through <code>less</code> and terminates that)</li> <li>if your script logger is enabled for <code>DEBUG</code> level logging, a full traceback will be shown for an uncaught exception</li> </ul> <p>Presumptions:</p> <ul> <li><p>you have a global <code>log</code> variable a la:</p> <pre class="prettyprint"><code>import logging log = logging.setLevel("scriptname") </code></pre></li> <li><p>your script's entry point is a function <code>def main(argv): ...</code></p></li> </ul>