Импорт в Python между тремя или более файлами не работает - PullRequest
0 голосов
/ 01 апреля 2009

У меня есть коды eg1.py, eg2.py, eg3.py eg3.py импортирует eg2.py, который в свою очередь импортирует eg1.py

Когда я запускаю eg3.py в первый раз, все в порядке Если я импортирую его снова и снова, только eg3.py запускается

Мне нужно решение для этого.

Я буду кодировать eg3.py таким образом, чтобы:

while(1):
    import eg2.py

Где я ошибся. Пожалуйста, дайте мне решение.

Ответы [ 3 ]

7 голосов
/ 01 апреля 2009

Хотите ли вы выполнить код в eg2.py при его импорте? Это не очень хорошее решение. У вас должна быть функция, содержащая ваш код в eg2.py, а затем выполнить эту функцию в цикле while.

В eg2.py:

def my_func():
    # do useful stuff
    pass

В eg3.py

import eg2
while True:
    eg2.my_func()
1 голос
/ 01 апреля 2009

А? Вы не можете зациклить import, они кешируются, поэтому после первой итерации он ничего не делает, кроме циклов траты

Откуда вы знаете, что "only eg3.py" работает?

0 голосов
/ 01 апреля 2009

Если вы импортируете модуль, который уже импортирован, исполняемый код в этом модуле не будет перезапущен.

например:.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> import this
>>> 

Удаление модуля из sys.modules приведет к полной перезагрузке:

например:.

>>> import sys
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> del(sys.modules["this"])
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

Edit: Кроме того, что сказал Хейкогерлах: вам лучше вызывать функции в уже импортированных модулях, чем удалять / перезагружать их большую часть времени.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...