简体   繁体   中英

How to fix Relative imports python problem

i want to import file that is in parent folder and i dont want to do this with sys

my files:

import/
   sub_folder/
       x.py
   a.py

file a.py:

def spam():
    print "gg"

file x.py:

from .. import a

def main():
    a.spam()

if __name__ == "__main__":
    main()

this is the error- Attempted relative import in non-package

I tryed all and nothing works

Relative imports don't work on files that get executed as the main file.

Relative imports depend on the __name__ attribute - which is set to __main__ if you're executing that file directly.

You need to execute that file as a package

python -m import.sub_folder.x

And you need to put some __init__.py files in the folders to make python recognize them as packages

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM