I have a Python script client.py that is called when I start my server.py (I cannot change this).
I want the client.py script to interact with the user, i.e., ask for input and show output, but as the client.py script has been called by the server, I cannot interact with it via console.
I'd like to know what is the simplest approach to asking for input from the client.py script, given that I cannot input to STDIN. I imagine two different approaches:
Is there any simpler option I'm not seeing?
You can make client.py temporarily override sys.stdin and sys.stdout with the system's console device whenever it needs to input from or output to the console, and restore sys.stdin and sys.stdout afterwards. In UNIX-like systems, the console device is /dev/tty, and in Windows, it is con.
For example, with a 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='')
and a server.py like:
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)
you can interact with server.py like:
Server says: Hello client
Enter something for the server: hi
Client says: hi
Demo: https://repl.it/@blhsing/CheeryEnchantingNasm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With