简体   繁体   中英

How to run function once without using decorators?

When y < x function should run only once and play only one sound, but when I run script it playes more than one. How to run it only once?

I tried to solve it with decorators, but I failed.

def random_choice(x, y):
    random_Process = [Process(target=play_sound0).start(),
    Process(target=play_sound1).start(),
    Process(target=play_sound2).start()]
    if y < x:
        random.choice(random_Process)


if __name__ == '__main__':
    random_choice(50, random.randint(40, 60))    

Expect: one and random

Process(target=play_sound1).start()

When run: three and random

Process(target=play_sound2).start()
Process(target=play_sound0).start()
Process(target=play_sound1).start()

This line

random_Process = [Process(target=play_sound0).start(),
    Process(target=play_sound1).start(),
    Process(target=play_sound2).start()]

starts all three Process instances. If you want to start only one, choose target :

targets = [
  play_sound0,
  play_sound1,
  play_sound2
]

target = random.choice(targets)
Process(target=target).start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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