简体   繁体   中英

Python: run script in background and do input/output

I need to make script that will be run in background, script will have always opened connection to memcached server and wating to get parametars from other program, when recive parametar script will do some work and output some information back to that first program. My bigest problem is how to make that script run in background and to wait for parametar?

Without knowing exactly how you're getting parameters from the other program, or how you're waiting, it's hard to give a specific answer.

But let's assume, for the sake of exposition, that it's listening for TCP connections to port 6789, and the other program just connects to that socket and sends a fixed number of parameters, separated by newlines.

The simplest way to do this is to just block:

memcache_connection = # however you set this up
sock = socket.socket()
sock.bind(('', 6789))
sock.listen(5)
while True:
    conn, addr = sock.accept()
    with contextlib.closing(conn) as client:
        with client.makefile() as f:
            param1, param2, param3 = f
        result = do_memcache_stuff(memcache_connection, param1, param2, param3)
        client.sendall(result)

Obviously there's no error-handling here, and no way to quit other than ^C, but that stuff is easy to add.

More seriously, it can only handle one command at a time. If that's a problem, you have the usual two choices: threading, or an event loop. Threading is generally simpler if you don't need to share information between two client connections and you don't need to handle more than a few dozen at a time. All you have to do is wrap up the handler in a function, then spawn it. So:

def handle_client(conn):
    with contextlib.closing(conn) as client:
        with client.makefile() as f:
            param1, param2, param3 = f
        result = do_memcache_stuff(memcache_connection, param1, param2, param3)
        client.sendall(result)

memcache_connection = # however you set this up
sock = socket.socket()
sock.bind(('', 6789))
sock.listen(5)
while True:
    conn, addr = sock.accept()
    t = threading.Thread(target=handle_client, args=(conn,))
    t.daemon = True
    t.start()

您想执行所谓的多线程,请在python文档中进行阅读或尝试一下:

import threading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM