简体   繁体   English

python不断更新线程中的全局变量

[英]python constantly updating a global variable in a thread

i'm using this library to handle a PN5180 rfid reader:我正在使用这个库来处理 PN5180 rfid 阅读器:

https://github.com/fservida/pyPN5180 https://github.com/fservida/pyPN5180

for what i understand in consist in one function named inventory() that return a list of up to 16 detected cards.据我了解,包含在一个名为 inventory() 的函数中,该函数返回最多 16 张检测到的卡片的列表。 you put it in a loop in order for it to update你把它放在一个循环中以便它更新

i'd like to be able to test how many cards are in the list at various times as well as returning some ids我希望能够在不同时间测试列表中有多少张卡片以及返回一些 ID

so i've tried putting the looped function into to a thread but i don't know ho to update it as a global variable in order to do my tests in the main program.所以我尝试将循环函数放入线程中,但我不知道如何将其更新为全局变量以便在主程序中进行测试。

def ListeningCards():

    print("listening to card thread started")
    while True:
        global cards    
        cards = PN5180().inventory()
        cardcount = len(cards)

th1 = threading.Thread(target = ListeningCards)

th1.start()


#main progam:

while true
#etc

so how can i achieve constant listening of the rfid chip and returning it in my main programme?那么我怎样才能实现对 rfid 芯片的持续监听并将其返回到我的主程序中呢? i tried multithreading but maybe there's other ways?我尝试了多线程,但也许还有其他方法?

cards is undefined until the first time the loop of ListeningCards is run.在第一次运行ListeningCards循环之前, cards是未定义的。 It may take a few milliseconds for the program to start running.程序开始运行可能需要几毫秒。 If your main program accesses cards before ListeningCards has had a chance to set it the first time, then you will get an undefined variable.如果您的主程序在ListeningCards有机会第一次设置它之前访问cards ,那么您将获得一个未定义的变量。

You might just want to set cards = 0 at the top of your program, or something like that, so that it has a default value.您可能只想在程序顶部设置cards = 0或类似的东西,以便它具有默认值。

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

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