0

I find it convenient to place my program entry point in a different file from __main__.py. Below are two example files located in the same package (test_1):

__main__.py:

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: ] ) )

main.py:

import sys

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

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

   return len( args )

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

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?

FluxIX
  • 325
  • 1
  • 2
  • 13

1 Answers1

1

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

FluxIX
  • 325
  • 1
  • 2
  • 13