Friday, May 17, 2013

A first iteration of sym.

The first iteration of sym runs in the background and does the following every 5 seconds:
  • checks if file, cmd.sym, exists, continues looping if it does not
  • if file contains "terminate" then sym stops running.
  • if file contains something else, sym just reads it and write it out to sym.log
# File: sym.py
# Author: hoekit [at] gmail [dot] com
from multiprocessing import Process
import os
import time

def sym_do(cmds):
    fp = open('sym.log','a')
    for x in cmds:
        if x.strip() == 'terminate':
            return False
        else:
            fp.write(x)
    return True

def sym_run():
    try:
        fname = 'cmd.sym'
        fp = open(fname,'r')
        commands = fp.readlines()
        fp.close()
        os.remove(fname)
        return sym_do(commands)
    except IOError:
        return True

def sym_loop():
    keep_running = True
    while keep_running == True:
        keep_running = sym_run()
        if keep_running == True:
            time.sleep(5)

if __name__ == '__main__':
    sym = Process(target=sym_loop)
    # sym.daemon = True
    sym.start()

These two links are great tutorials on how to spawn processes in Python:
* http://pymotw.com/2/multiprocessing/basics.html
* http://pymotw.com/2/multiprocessing/communication.html

1 comment:

  1. The process does not exactly run in the background and setting the daemon = True doesn't help.
    Suggestions to consider include:
    Using os.spawn[1] or running as a service[2].

    Ref:
    1: http://stackoverflow.com/questions/6448217/run-a-bat-program-in-the-background-on-windows
    2: http://stackoverflow.com/questions/263296/creating-a-python-win32-service

    ReplyDelete