我正在运行一个Python脚本,它将在板上显示消息。我创建的子例程之一应该从一个小的文本文件中抓取一条随机行,并显示该行。它通常有效,除了循环几次后,它卡在了相同的数字上,并且一遍又一遍地显示相同的内容。
我正在Raspbian的Raspberry Pi上的Python 2.7中运行它。我使用此github作为项目的基础,并在其中添加了自己的代码行:https://github.com/CalebKussmaul/Stranger-Things-Integrated这是万圣节展览的一部分,该展览将以“陌生人事物”为主题,因此预先加载的消息会引用该展览。前几天,我注意到了这个问题,并且一直在互联网上倾泻,试图找出问题所在。我尝试了选择随机数的不同方法,包括该站点上一些类似(但不同)线程中的一些方法。它们都产生完全相同的问题。
下面是我创建的子例程:
def preloaded_messages():
print "Preloaded Messages thread is loaded."
global displaying
while True:
if not displaying:
with open('preloaded_messages.txt') as f:
lines = len(f.readlines())
rgn = random.randint(1,lines)
msg = linecache.getline('preloaded_messages.txt', rgn)
print "rng: ", rgn
print "total lines: ", lines
print "line: ", msg
print "displaying from preloaded_messages.txt: ", msg
display(msg)
time.sleep(10)
这是我的preloaded_messages.txt文件:
help me
im trapped in the upside down
leggo my eggo
friends dont lie
run /!
hopper is alive
rip barb
demogorgon is coming /!
mouthbreather
当我运行它时,我的输出是这样的:
rng: 6
total lines: 9
line: hopper is alive
rng: 2
total lines: 9
line: im trapped in the upside down
rng: 9
total lines: 9
line: mouthbreather
...
rng: 9
total lines: 9
line: mouthbreather
最初的几次总是随机的(成功随机化的次数也有所不同),但是当它达到9时,只要我允许它运行,它就会一直停留在那里。我不知道为什么它会在头几次工作,但是一旦达到9就不会了。
编辑:有趣的是,正如我一直在写这篇文章一样,我也尝试在末尾添加一个空行,虽然看起来好像又被卡住了,因为它连续三次执行了一次,然后终于搬到别人了。我不确定这会如何改变。理想情况下,我宁愿不要在其中有空白行,因为它会浪费时间显示任何内容。因此,很高兴解决此问题。有人有什么想法吗?
这似乎对我有用:
导入时间随机导入从datetime导入datetime
def preloaded_messages():
print("Preloaded Messages thread is loaded.")
displaying = False
while True:
if not displaying:
with open('preloaded_messages.txt') as f:
random.seed(datetime.utcnow())
text = f.read().splitlines()
msg = random.choice(text)
print("line: ", msg)
# print("displaying from preloaded_messages.txt: ", msg)
time.sleep(10)
if __name__ == "__main__":
preloaded_messages()