一个 Python 脚本的多个控制台窗口 [英] multiple console windows for one Python script

查看:20
本文介绍了一个 Python 脚本的多个控制台窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过类似的问题,例如:从批处理中打开多个控制台窗口.

I've seen similar questions such as this one: keep multiple console windows open from batch.

但是,我有不同的情况.我不想在不同的控制台窗口中运行不同的脚本.我的想法是让套接字作为服务器运行并接受所有连接.当一个连接被接受时,一个新的控制台窗口被创建,所有传入和传出的数据都显示在那里.这可能吗?

However, I have a different situation. I do not want to run a different script in a different console window. My idea is to have socket running as a server and accepting all connections. When a connection is accepted, a new console window is created, and all in-coming and out-going data is shown there. Is that even possible?

推荐答案

一个进程一次只能附加到一个控制台(即conhost.exe的实例),没有附加进程的控制台会自动关闭.您需要使用 creationflags=CREATE_NEW_CONSOLE 生成子进程.

A process can only be attached to one console (i.e. instance of conhost.exe) at a time, and a console with no attached processes automatically closes. You would need to spawn a child process with creationflags=CREATE_NEW_CONSOLE.

以下演示脚本需要 Windows Python 3.3+.它产生两个工作进程,并通过 socket.sharesocket.fromshare 将每个套接字连接复制到工作进程中.编组的套接字信息通过管道发送到孩子的 stdin.加载套接字连接后,管道关闭,CONIN$ 作为 sys.stdin 打开以从控制台读取标准输入.

The following demo script requires Windows Python 3.3+. It spawns two worker processes and duplicates each socket connection into the worker via socket.share and socket.fromshare. The marshaled socket information is sent to the child's stdin over a pipe. After loading the socket connection, the pipe is closed and CONIN$ is opened as sys.stdin to read standard input from the console.

import sys
import time
import socket
import atexit
import threading
import subprocess

HOST = 'localhost'
PORT = 12345

def worker():
    conn = socket.fromshare(sys.stdin.buffer.read())
    sys.stdin = open('CONIN$', buffering=1)
    while True:
        msg = conn.recv(1024).decode('utf-8')
        if not msg:
            break
        print(msg)
        conn.sendall(b'ok')
    input('press enter to quit')
    return 0

def client(messages):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        for msg in messages:
            s.sendall(msg.encode('utf-8'))
            response = s.recv(1024)
            if response != b'ok':
                break
            time.sleep(1)

procs = []

def server():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen(1)
        while True:
            conn, addr = s.accept()
            with conn:
                p = subprocess.Popen(
                    ['python', sys.argv[0], '-worker'],
                    stdin=subprocess.PIPE, bufsize=0,
                    creationflags=subprocess.CREATE_NEW_CONSOLE)
                p.stdin.write(conn.share(p.pid))
                p.stdin.close()
                procs.append(p)

def cleanup():
    for p in procs:
        if p.poll() is None:
            p.terminate()

if __name__ == '__main__':
    if '-worker' in sys.argv[1:]:
        sys.exit(worker())

    atexit.register(cleanup)

    threading.Thread(target=server, daemon=True).start()

    tcli = []
    for msgs in (['spam', 'eggs'], ['foo', 'bar']):
        t = threading.Thread(target=client, args=(msgs,))
        t.start()
        tcli.append(t)

    for t in tcli:
        t.join()

    input('press enter to quit')

这篇关于一个 Python 脚本的多个控制台窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆