__main__.py Behavior Different Between Python 2 and 3
<p>I find it convenient to place my program entry point in a different file from <code>__main__.py</code>. Below are two example files located in the same package (<code>test_1</code>):</p>

<p><code>__main__.py:</code></p>

<pre><code>import sys
from main import main as entry_point

if __name__ == '__main__':
    script_name = sys.argv[ 0 ]

    print( "Script name: {}".format( script_name ) )

    sys.exit( entry_point( sys.argv[ 1: ] ) )
</code></pre>

<p><code>main.py:</code></p>

<pre><code>import sys

def main( args = None ):
   if args is None:
       args = sys.argv[ 1 : ]

   print( "Program arguments are: {}".format( str( args ) ) )

   return len( args )
</code></pre>

<p>When invoking the script with <code>python3 -m test_1 1 2 3 4</code>, I get the following error: "ImportError: No module named 'main'", but when invoked with <code>python2 -m test_1 1 2 3 4</code> I get the expected behavior of executing the script.</p>

<p>Why does the importation work differently between python2 (2.7.12) and python3 (3.5.2) and what do I need to do to accomplish the behavior I am trying to achieve?</p>

<p>For Python 3, the <code>__main__.py</code> needs to use an explicit relative import, so <code>from .main import main as entry_point</code> instead of <code>from main import main as entry_point</code>.</p>

python python-2.7 python-3.x