tags:

views:

70

answers:

4

Hello,

I was hoping to get some help on a question. I have an infinite loop that I need run and I need to update a set of variables (x in this case) at random times from the command-line. Is there any way to do this?

For example:

x = 0
while True:
 x  = x + 1 
 if x < 30:
  do something

and I need to update x's value from the command-line periodically

A: 

Once the program is running and inside that loop, theres no way externally to modify the parameters passed into that program. What you will do is have this program running, and run a seperate program to send a message into this one while its running to modify state. Inside your infinite loop you will need to have code to look for and receive that message and take effect. There are lots of methods to perform this communications. The most basic version would be to periodically poll a file every so many iterations in your infinite loop. If the file contents have changed, read them in and thats the new value of X. Then to change the variable from the command line you just run a command like

 echo "NewValue" > file.txt

Files would work here, though something like pipes would be more appropriate.

bdk
+1  A: 

To me it sounds like a better way to implement this would be to use a thread instead of an infinite loop and use the

notify()

method to instruct when to update with data from command line

Here is a good reference to get you started:

http://docs.python.org/library/threading.html

David Relihan
+1  A: 

This is rather hackish, but kinda cute:

import code
import signal
import time
def signal_handler(signal, frame):
    code.interact(local=globals())
signal.signal(signal.SIGINT, signal_handler)

x=0
while True:
    x  = x + 1
    time.sleep(0.01)
    if x < 30:
        print(x,'do something')

When you press Ctrl-C, you are dropped to the python interpreter. There you can type Python statements like

x=10

Pressing Ctrl-D resumes execution.

unutbu
+1, interesting solution...
João Portela
A: 

My Solution Using Threads and basic locking mechanism.

from threading import Thread,Lock

lock = Lock()

def read():
    global x
    x = 0
    while True:
        lock.acquire()
        try:
            x  = x + 1 
        finally:
            lock.release()
        if x < 30:
            #do something


def update():
    global x
    while True:
        cmd_input = int(raw_input())
        lock.acquire()    
        try:
            x = cmd_input
        finally:
            lock.release()

if __name__=='__main__':
    update_t = Thread(target=update,args=())
    read_t = Thread(target=read,args=())
    update_t.start()
    read_t.start()
Ashish