Search code examples
pythonpersistenceround-robin

python: how can I get a new value in round robin style every time i invoke the script


I have a file called subnets which contains a list of available subnets in the system. I want that my script should return to me one subnet at each script invocation, in round robin style.

Example:

subnets file:

subnet1
subnet2
subnet3

expected output:

python next_available_subnet.py    
output: subnet1

python next_available_subnet.py    
output: subnet2

python next_available_subnet.py    
output: subnet3

python next_available_subnet.py    
output: subnet1

How can I achieve this? I have tried global variables, iterators , but i lose the value by the time i invoke the script again and it always gives the same subnet as output.


Solution

  • As other answers have pointed out, you will need some external way to provide persistency between executions. You could use a separate file, a database record, or some other long-running process.

    However, you could also use the subnets file itself to provide the persistency. Just read the file, print the top value and then rotate its contents, ready for the next run.

    This example uses a deque to implement the rotation:

    import os
    import collections
    
    subnets_file = "subnets.txt"
    
    # Load the subnets file into a deque
    with open(subnets_file, 'r') as f:
        subnets = collections.deque(f.read().splitlines())
    
    # Print the top subnet
    print subnets[0]
    
    # Rotate the subnets
    subnets.rotate(-1)
    
    # Save the rotated subnets
    with open(subnets_file, 'w') as f:
        for s in subnets:
            f.write("%s\n" % s)
    

    when run:

    $ python next_available_subnet.py 
    subnet1
    $ python next_available_subnet.py 
    subnet2
    $ python next_available_subnet.py 
    subnet3
    $ python next_available_subnet.py 
    subnet1