Search code examples
simpy

Simpy: How to catch the return value of a simpy process


Imagine that I have this scenario:

def my_process(env, run_length):
    count = 0
    while True:
        env.timeout(1)
        count += 1
        if env.now >= run_length:
            break

    return count

my_env = simpy.Environment()

count = my_env.process(my_process(my_env, 100))

my_env.run(100)

If I print the value of count it will return the the generator itself and not the count of the number of events triggered by the generator which is what I want. I could pass an object to my_process and change its state according to count, but isn't there another way?

Thank you very much in advance!!


Solution

  • You should use yield and another process for getting return value. (Environment's run time should be more than 100).

    import simpy
    
    def my_process(env, run_length):
        count = 0
        while True:
            yield env.timeout(1)
            count += 1
            if env.now >= run_length:
                break
    
        return count;
    
    def first_process(env, run_length):
        return_value = yield env.process(my_process(env, run_length))
        print("return value: ", return_value)
    
    my_env = simpy.Environment()
    my_env.process(first_process(my_env, 100))
    my_env.run(101)
    

    output in simpy 4:

    return value:  100