0

I'm using Visual Studio Code.

Suppose my folder looks like:

├── main.py
└── package
    ├──__init__.py
    ├──utils.py
    └──method.py

In my method.py, I import the utils.py, which is in the same directory, so I put the dot before the name:

from .utils import *

then I can run the script in main.py like:

from package import method

This will work. But the question is, how I can run the script in method.py at its directory instead of importing it in main.py? If I run the script method.py directly, an error will occur:

ModuleNotFoundError: No module named '__main__.modules'; '__main__' is not a package

What can I do to run the script in method.py without removing the dot as from utils import *?

2
  • Did you try running python -m package.method ? Commented Dec 30, 2019 at 9:14
  • Can you add code for method.py? I think, somewhere you're trying to do from __main__ import something Commented Dec 30, 2019 at 9:29

2 Answers 2

2

To make your code work, change the import statement in method.py from

from .utils import *

to

import __main__, os

if os.path.dirname(__main__.__file__) == os.path.dirname(__file__):
    # executed script in this folder
    from utils import *
else:
    # executed script from elsewhere
    from .utils import *

When method.py runs, it checks the folder that the executed python script is in, and if it's the same folder as itself, it will import utils, rather than .utils.

You can achieve a similar thing using

if __name__=='__main__':

as your check. However, if method.py is imported by anther file inside the package folder, then method.py will try to import .utils, and won't be able to find it.

Sign up to request clarification or add additional context in comments.

Comments

-1

If you are here and the above solutions did not work for you, then please check if your newly defined custom class has blank lines after its definition - it needs those lines to work. enter image description here

if it looks like below, it won't work enter image description here

1 Comment

Whether blank lines exist or not should have no effect whatsoever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.