About Python import.external file loading

Asked 2 years ago, Updated 2 years ago, 133 views

I want to load an external file and use it, but it doesn't work.Please let me know.

environment
CentOS 7
Python 3.7
Django 2

tree
.app1
| - aa.py Loaded Files
| - bb.py Import Files

aa.py

def hoge:
  print('hogehoge')

bb.py

from.import aa
aa.hoge()

From Django, it certainly works on bb.py, but when I run on python bb.py, I get the following error:

from.import aa
ImportError: cannot import name 'aa' from '__main__' (bb.py)

However, if you change from.import aa to import aa on bb.py, it will also work on python bb.py

Now, I have a question, what should I do if I want to run bb.py with the same code in Django and locally?
Please let me know.

python python3 django

2022-09-30 21:33

1 Answers

Why don't you put run.py in the same directory as the app1 directory and start it?

#coding:utf-8
import app1.bb

Python's import system is a bit cool, so I don't know if I can explain it properly, and I don't know if this is the case in the first place.
Please listen to the following with that in mind.

Relative imports such as .from.import aa 」 appear to be available only between submodules in the same package.

To put it a little more clearly (maybe not), for example,

sys.path+=['.']
import app1.bb

In this case, appapp1 」 becomes the package, and aa.pybb.py 「 and 」 は 「 under it are submodules of the 1app1 の package, so you can import romfrom.import aa 」.

However,

sys.path+=['./app1']
import bb

Then したbb 」 becomes the package, so 」aa.py は is considered to be a module in a different package.

I've never used django before, so I'm not sure, but I think bb.py has been imported in the former pattern.

Another thing I want to know is why bb.py, which is called import aaa, is successful if you run it as python bb.py.
This is not a direct reason for because "aa.py" is in the same directory as "bb.py".

The procedure result in importing 」aa.py が in the same directory as bb.py 」 と.

Based on the above information, it may be the reason that relative import is not available when running bb.py directly.

I wrote it in detail, but while I was writing, I thought of another countermeasure.

 if__name__=='__main__':
  import aaa
else:
  from.import aa

But I think it's okay.
I don't know if it works with django.


2022-09-30 21:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.