简体   繁体   English

Python:在后台运行脚本并执行输入/输出

[英]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. 但是,为了说明起见,我们假设它正在侦听到端口6789的TCP连接,而另一个程序只是连接到该套接字并发送固定数量的参数(由换行符分隔)。

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. 显然,这里没有错误处理,除了^ C之外没有其他方法可以退出,但是这些东西很容易添加。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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