Sunday, 14 February 2021

Supply stdin input to subprocess.Popen() after execution of the process had begun ( and before it had finished )

I'm making a program with a remote shell utility in Python3, using sockets and subprocess. Everything works perfectly so far but i have encountered an issue i can't find the solution for. Here is the code on my server script which executes a command received from the client:

process = subprocess.Popen(client_buffer.decode('utf-8').split(), stdout = subprocess.PIPE) # Creating a process
        while True: # Reading and sending the stdout from the process in realtime
            shell_output = process.stdout.readline() # Read a line from stdout
            return_code = process.poll()
            print(shell_output)
            print(return_code)
            if shell_output.decode('utf-8') == '' and return_code is not None: 
                #print("Process execution complete. Sending user prefix")
                send(client, ("<#" + color.user + getpass.getuser() + color.endc + "@" + color.dir + cwd() + color.endc + ">").encode('utf-8'))
                break
            elif shell_output: 
                # Process execution incomplete, signaling to client with code 2
                send(client, int_to_bytes(2))
                # And sending the next line of stdout
                send(client, shell_output)

All works well and i was satisfied, but there is one limitation that i can't figure out how to remove. Namely, i can easily supply the server with a command with arguments and the server will execute it and send the output back, that works well, but if the program started by the command asks for additional input (for example a "(y/n)" question) before the execution of the process is over (mid-execution), i do not know how to supply the input to the process.

Can i do this with subprocess.Popen()? Any clue will be helpful and i thank You in advance. I forgot to add, the program is meant to be used in Linux.

P.S Any functions and variables of which definitions/declarations i haven't provided in the code sample are irrelevant, but the project can be found on my github incase anyone wants to see more of the code



from Supply stdin input to subprocess.Popen() after execution of the process had begun ( and before it had finished )

No comments:

Post a Comment