Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to interact with a Python script that is called by another program?

Tags:

python

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?

like image 300
josealeixo.pc Avatar asked Jan 23 '26 12:01

josealeixo.pc


1 Answers

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

like image 114
blhsing Avatar answered Jan 25 '26 02:01

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!