简体   繁体   English

导入后如何从导入的模块更新列表?

[英]How to update a list from an imported module once imported?

test.py test.py

import threading

a_list = []
def a():
    while True:
        a_list.append("A")

threading.Thread(target=a).start()

test1.py test1.py

import test
from test import a_list
import time

while True:
    print(a_list)
    time.sleep(1)

if I import the file "test" and infinitely append "A" into a list and use "test1" to print the values, for some reason the values WILL NOT update for test1 如果我导入文件“ test”并无限地将“ A”附加到列表中并使用“ test1”来打印值,则由于某种原因,值将不会为test1更新

How can I make test1 recognise that the list has been updated from file "test" and print it out using the file "test1" 如何使test1识别出该列表已从文件“ test”更新,并使用文件“ test1”将其打印出来

I rushed this code to share in here, I am sorry about that. 我急于将此代码分享到这里,对此我感到抱歉。 Some help would be nice. 一些帮助会很好。 I tried googling it but I couldn't find anything 我尝试使用Google搜索,但找不到任何东西

You forgot global in your function: 您忘记了global功能:

import threading

 a_list = []
 def a():
      global a_list
      while True:
         a_list.append("A")

 threading.Thread(target=a).start()

Althougth I recommend against such code. 我建议不要使用此类代码。

Beware: "Here be dragons" 当心:“这里是龙”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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