python - 与另一个程序调用的 Python 脚本交互的最简单方法是什么?
问题描述
我有一个 Python 脚本client.py
,当我启动时会调用它server.py
(我无法更改它)。
我希望client.py
脚本与用户交互,即要求输入并显示输出,但由于client.py
脚本已被服务器调用,我无法通过控制台与之交互。
client.py
鉴于我无法输入到 STDIN,我想知道从脚本中请求输入的最简单方法是什么。我想象两种不同的方法:
- 使用 GUI(如 TKinter)。但是我必须将我的所有脚本移动到一个线程中,因为 GUI 的主循环需要位于主线程上。
- 使用套接字并通过终端或网页连接。但这感觉有点矫枉过正。
有没有我没有看到的更简单的选择?
解决方案
您可以在需要从控制台输入或输出到控制台时client.py
临时覆盖sys.stdin
和使用系统的控制台设备,并在之后恢复。在类 UNIX 系统中,控制台设备是,而在 Windows 中是。sys.stdout
sys.stdin
sys.stdout
/dev/tty
con
例如,有一个client.py
like:
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
推荐阅读
- wordpress - Sabre WordPress 集成
- vue.js - Vuejs- if..else 语句中未达到第二个 axios.get
- javascript - 如何在 p5.js 中获得顶视图房子
- excel - 用条目将特定范围与最后一行相邻是什么错误?
- linux - 使用 github 操作在 Linux 下构建基于 Qt5 的 Windows 程序的最简单/最快的方法?
- c# - 每当使用具有唯一文件名的 serilog 执行控制台 appln 时,我都想创建新的日志文件
- android - RenderBox 未布置:RenderConstrainedBox#358ca relayoutBoundary=up12 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
- node.js - NodeJS请求得到返回我的html代码而不是json
- c++ - 我的程序在第一次迭代后不会接受输入
- c++ - 将 3D 图像从 C++ 导出到 Matlab .fig 文件