Generate a value from a list on an Expression tag

I am trying to create an Expression tag to generate values randomly from a list for testing purposes. The code below works on the Scripting Console, but not when I create an Expression tag. Can you help me to see what I am missing, please? Thanks.


import random
import time

# Define a list of values
values = ['1', '2', '3', 'A', 'B', 'C']

# Generate a value from the list every second
while True:
    print random.choice(values)  # Selects a random value from the list
    time.sleep(1)  # Waits for 1 second

You'll need to create a script in your scripting library on the gateway configured gateway scripting project (this is key!!) If you don't have a gateway scripting project configured, you'll need one for this to work at all.

Next, you'll create the following script:

import random

def getRandomSelection():
    # Define a list of values
    values = ['1', '2', '3', 'A', 'B', 'C']

    # Selects a random value from the list
    return random.choice(values)  

Then for your expression tag you'll need to call this function/script (assuming it's named "RandomValues" just for this example):

runScript('RandomValues.getRandomSelection')

Set exectution mode to fixed rate, and define your execution rate (default is 1000ms)

Edit: moved the import out of the fuction per @PGriffith suggestion.

4 Likes

If you're in the project library, you should import outside the function definition, so you're only doing it once, not every time the function is called.

Otherwise, stellar advice. You could leave the tag in 'execution driven' and use the poll rate parameter on runScript to define your execution rate, but there's really no difference.

I'd also, just for personal taste, think that the selection function should accept an input list to sample over, but that's not in the original post so who knows their requirement.

3 Likes

There is also this generic simulator program if you need random values.

1 Like

Yea, I'd probably do this:

from random import choice

def random_choice(*options):
	return choice(options)
3 Likes


OK, this is how far I get, but I am geeting an error on the Expression evaluation.

Make sure your project (XYL1001) is set as the Gateway Scripting Project:

Also, your datatype will need to be set to String since you're passing not only integers, but letters/characters.

3 Likes

That was it! It wasn't pointing to my project. Now it is working! Thanks a lot, everyone! I learned something new today! :nerd_face:

Yep, that one's gotten me a couple times.

1 Like