Obsidian
Obsidian

Reputation: 947

How to run a Python code inside a custom package?

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 *?

Upvotes: 0

Views: 460

Answers (2)

Arkadiusz Kulpa
Arkadiusz Kulpa

Reputation: 117

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

Upvotes: -1

Ed Ward
Ed Ward

Reputation: 2331

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.

Upvotes: 2

Related Questions