Python:如何从仍在运行的进程中退出并等待输出

时间:2019-04-10 16:14:34

标签: python sockets

因此,我有server监听连接,并且客户端向server发送了消息

clientserver的消息包含server计算机上存在的文件路径

客户

import sys
import socket

# Validate arguments.
if len(sys.argv) < 3:
    raise Exception('\n\nYou must specify at least 2 arguments:\n1. Server ip address.\n2. Message to server.')

# Validate server ip address.
try:
    socket.inet_aton(sys.argv[1])
    ip = sys.argv[1]
except socket.error:
    raise Exception('{ip} is not valid IPv4 address'.format(ip=sys.argv[1]))

# In case message contains spaces, Join.
message = ' '.join(sys.argv[2:])
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 4500
address = (ip, port)

client = socket.socket()
client.connect(address)
client.sendall('{message}'.format( message=message).encode('utf-8'))

response = client.recv(1024).decode('utf-8')
print(response)

服务器

import socket
import subprocess


def process_message(file, client):
    process = subprocess.Popen([file], stdout=subprocess.PIPE)
    while True:
        output = process.stdout.readline()
        str-output.decode('utf-8')
        client.send(str)

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(5)

while True:
    client, address_info = server.accept()
    while True:
        data = client.recv(1024).decode('utf-8')
        process_message(data, client)
        client.close()
        break

因此,正如您在我的server代码中所看到的那样,我接受client消息(file path)并打开进程(运行此文件,通常是batch文件)读取输出,然后将每一行返回到client

我的问题是,当我启动batch appium时启动server文件,因为在这种情况下appium process继续运行,而我的代码只是堆叠并等待output,而我要做的就是等待process output中的特定行(例如listening on)并退出。

有什么建议吗?

0 个答案:

没有答案