Python随机.randint循环几次后停止随机化

2024-09-27 04:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个python脚本,它将在一个板上显示消息。我创建的一个子例程应该从一个小文本文件中随机获取一行,并显示该行。它基本上是工作的,除了在循环几次之后,它被固定在同一个数字上,并且一遍又一遍地显示相同的东西。你知道吗

我在Python2.7中运行这个,在Raspbian的Raspberry Pi上运行。我将此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)

这是我预装的_消息.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次就不行了。你知道吗

编辑:有意思的是,在我写这篇文章的时候,我还试着在结尾加一个空行,虽然看起来像是又卡住了,因为它连续做了三次,最后它移到了其他人那里。我不知道这会改变什么。理想情况下,我宁愿不要空白行,因为它占用了时间,什么也不显示。所以最好能解决这个问题。有人有什么想法吗?你知道吗


Tags: txt消息islinemsg例程totalmessages
2条回答

这似乎对我有用。请注意,我正在播种RNG。你知道吗

import time
import random
from datetime import 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()

它正在给随机发生器重新播种。见第49行陌生人.py在https://github.com/CalebKussmaul/Stranger-Things-Integratedrandom.seed(i)中。你知道吗

color_of函数应编写为:

def color_of(i):
    """
    This function generates a color based on the index of an LED. This will always return the same color for a given
    index. This allows the lights to function more like normal christmas lights where the color of one bulb wont change.

    :param i: index of LED to get color of
    :return: a pseudorandom color based on the index of the light
    """
    _random = random.Random(i)
    rgb = colorsys.hsv_to_rgb(_random.random(), 1, 1)
    return int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)

用给定的种子创建它自己的Random实例,而不是在random模块中重新播种作为单例的Random实例。你知道吗

相关问题 更多 >

    热门问题