如何暂停线程直到在Python中接收到数据

时间:2018-08-13 11:29:28

标签: python sockets networking

我对线程(和一般的网络)没有太多经验。我正在创建一个从客户端(123)接收数据的脚本。所有这些都有一个含义:

1   =   NEW Apache Benchmark ITERATION - we must run new top command and append every second
2   =   END Apache Benchmark ITERATION - we must end top command
3   =   STOP ENTIRE PROGRAM

Linux上的top命令仅记录CPU和内存使用情况。

我创建了一个初始线程,该线程侦听来自客户端的数据并以get_data()函数为目标。

run()函数等待从get_data()返回数据,但是如果没有获取任何数据,则run()get_data()函数都将停止。

是否有一种方法可以暂停面向get_data函数的线程,直到从客户端发送数据,以便run()函数不会停止?

我当前的代码:

import socket
import sys
import threading
import subprocess
import sched
import time
import os
import signal

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_socket = ('xxx.xxx.x.xx', 5000)
sock.bind(server_socket)


process = None

def run_command(i):
    global process
    print("Running top")
    process = subprocess.Popen('top -b -n 1 | head -n 5 >> htop-' + str(i)  + '.txt', shell=True)
    print("Finished running top")

    return process

def get_data():
    while True:
        # data = ''
        data, address = sock.recvfrom(1024)
        print("waiting?")

        data = data.split(",")
        iteration = data[1]
        data = data[0]

        print("Data: " + data + " and iteration: " + iteration)

        time.sleep(1.0)

        # run(data, iteration)
        return data, iteration

'''
    1   =   NEW AB ITERATION - we must run new top command and append every second
    2   =   END OF AB - we must end top command
    3   =   STOP ENTIRE PROGRAM
'''

def run():
    while True:
        print("New")
        data = get_data()
        # data = data.split(",")
        iteration = data[1]
        data = data[0]

        print("Data: " + data + " and iteration: " + iteration)

        if data == '1' or data == '':
            run_command(iteration)
            print("We ran the command")

            time.sleep(1.0)

            print("Terminating")
            process.kill()
            print("We terminated the process")

        if data == '2':
            print("We got 2")
            process.kill()

        if data == '3':
            print("Closing program")
            exit()


runThread = threading.Thread(target = run)
runThread.start()


run()

print("Starting the listening thread...")

1 个答案:

答案 0 :(得分:0)

您需要使套接字无阻塞(请参见setblocking()),并重写run()过程以处理尚未收到套接字中数据的情况。