3

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:

  • Using a GUI (like TKinter). But I would have to move all my script into a thread because the main loop of the GUI will want to be on the main thread.
  • Using sockets and connecting either via terminal or webpage. But this feels like an overkill.

Is there any simpler option I'm not seeing?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'd forgotten about pipes. I'll try this out. I am considering this the right answer because I believe it's the simplest choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.