Starting a process and sending subsequent commands using Process library

Hello.
I am writing a test that interacts with a python script, the most straightforward use case would be to start the python script via process, show a prompt expecting input and send additional commands, then expect another prompt and again send commands. Doing that until the process exits manually or finishes.

To do so I am intending to start a process and send additional commands to the stdin of the started process.
I can start it, however I don´t seem to be able to send the next commands.

This is just a simple example of what it could look like.

#mockup_test.robot
${SCRIPT_PROCESS}= Start Process python ${SCRIPT_PATH} stdout=PIPE

${result}= Run Process exit stdin=${SCRIPT_PROCESS.stdout}

#mockup_python_script.py

import time
import sys

def simulate_device_action():
“”“Simulates a device action and returns a status code.”“”
import random
status_codes = [“200”, “404”, “500”]
return random.choice(status_codes)

def main():
# Check if maintenance mode is enabled
if “–maintenance-mode” in sys.argv:
print(“Script started in maintenance mode”)

# Simulate listening for commands
while True:
    try:
        command = input("Awaiting command: ")
        if command == "exit":
            print("Exiting script...")
            break
        elif command == "continue":
            print(f"Processing command: {command}")
            time.sleep(1)
            print("Command executed successfully.")
        else:
            print(f"Received unknown command: {command}")
            print(f"Simulating action...")
            time.sleep(1)
            status = simulate_device_action()
            print(f"Action completed with status: {status}")
    except KeyboardInterrupt:
        print("\nScript interrupted by user.")
        break

if name == “main”:
main()

Can someone help me figuring out what is the most straightforward way to achieve this?

Thanks.

Try to learn about the subprocess module. Although the examples are for external commands, this link, you can use for your goals.

See the official docs of subprocess here.

Here in asyncio module there is more information.

Maybe you can also see threading, here.

1 Like