gpt4 book ai didi

python - 与另一个程序调用的 Python 脚本进行交互的最简单方法?

转载 作者:行者123 更新时间:2023-12-04 04:13:38 25 4
gpt4 key购买 nike

我有一个 Python 脚本 client.py,当我启动 server.py 时会调用它(我无法更改它)。

我希望 client.py 脚本与用户交互,即要求输入并显示输出,但是由于 client.py 脚本已被调用服务器,我无法通过控制台与其交互。

我想知道从 client.py 脚本请求输入的最简单方法是什么,因为我无法输入到 STDIN。我想象两种不同的方法:

  • 使用 GUI(如 TKinter)。但是我必须将我的所有脚本移动到一个线程中,因为 GUI 的主循环将要在主线程上。
  • 使用套接字并通过终端或网页进行连接。但这感觉有点矫枉过正。

有没有我没看到的更简单的选项?

最佳答案

您可以使 client.py 在需要输入时使用系统的控制台设备临时覆盖 sys.stdinsys.stdout或者输出到控制台,然后恢复sys.stdinsys.stdout。在类 UNIX 系统中,控制台设备是 /dev/tty,在 Windows 中,它是 con

例如,client.py 如下:

import sys

original_stdin = sys.stdin
original_stdout = sys.stdout
console_device = 'con' if sys.platform.startswith('win') else '/dev/tty'

def user_print(*args, **kwargs):
sys.stdout = open(console_device, 'w')
print(*args, **kwargs)
sys.stdout = original_stdout

def user_input(prompt=''):
user_print(prompt, end='')
sys.stdin = open(console_device)
value = input('')
sys.stdin = original_stdin
return value

user_print('Server says:', input())
print(user_input('Enter something for the server: '), end='')

和一个 server.py 像:

from subprocess import Popen, PIPE

p = Popen('python client.py', stdin=PIPE, stdout=PIPE, encoding='utf-8', shell=True)
output, _ = p.communicate('Hello client\n')
print('Client says:', output)

您可以像这样与 server.py 交互:

Server says: Hello client
Enter something for the server: hi
Client says: hi

演示:https://repl.it/@blhsing/CheeryEnchantingNasm

关于python - 与另一个程序调用的 Python 脚本进行交互的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61212545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com