首页 > 解决方案 > 与另一个程序调用的 Python 脚本交互的最简单方法是什么?

问题描述

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

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

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

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

标签: python

解决方案


您可以在需要从控制台输入或输出到控制台时client.py临时覆盖sys.stdin和使用系统的控制台设备,并在之后恢复。在类 UNIX 系统中,控制台设备是,而在 Windows 中是。sys.stdoutsys.stdinsys.stdout/dev/ttycon

例如,有一个client.pylike:

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


推荐阅读