How to import one submodule from different submodu

2019-07-06 05:02发布

问题:

This question already has an answer here:

  • Relative imports for the billionth time 9 answers

My project has the following structure:

DSTC/
    st/
        __init__.py
        a.py
        g.py
        tb.py
    dstc.py

Here is a.py in part:

import inspect
import queue
import threading

Here is tb.py in part:

import functools
from . import a

When run directly, a.py produces no errors, and it is easy to verify there were no SyntaxErrors. However, running tb.py causes the following error:

"C:\Program Files\Python36\python.exe" C:/Users/user/PycharmProjects/DSTC/st/tb.py
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/DSTC/st/tb.py", line 15, in <module>
    from . import a
ImportError: cannot import name 'a'

Process finished with exit code 1

How should I rewrite the import of a from tb so that tb can be run directly without causing errors?

回答1:

Either you can use

import a

or relative

from .a import *

and in this case module **a** should be loaded

python -m a tb.py

will works for you.

import * is discouraged, import just as you need

If you got a main.py in your DSTC as follows:

#  main.py
from st import tb

and you run main.py only relative approach will work for you

# tb.py 
import a  # will not work
from .a import * # will work

because this time you load 'a' as a module.



回答2:

you only require to import only module a.

import a


回答3:

Use import .a or, better, import st.a. These will only work if you are importing tb as part of your package (e.g. using python -m switch from parent directory) rather than running it like a script.

As others have said, simplyimport a will work. This has to advantage of working regardless of whether st is run as a module or script, but it's bad practice and only works on python 2, not python 3.

The same applies to the from variants that others have mentioned.