Zipzap
Zipzap

Reputation: 39

Python subprocess, give an input to a child process

I made a program that checks a secret key. and another program that supposed to find the secret key. I managed to open a child process in the second program but couldn't send it an input. Here's the program that checks a secret key, secret_key.py:

SECRET_KEY = "hi"
current_key = 0

while not current_key == "exit":
    wrong_key = False
    current_key = raw_input("Enter the key or enter 'exit' to exit.\n")

    for i in range(len(current_key)):
        if i < len(SECRET_KEY):
            if not current_key[i] == SECRET_KEY[i]:
                wrong_key = True
        else:
            wrong_key = True

    if not wrong_key:
        print("the key is right!\n")
        current_key = "exit"

raw_input("Press ENTER to exit\n")
exit()

Now i made a .sh file to be able to run it in a new terminal as a child process, program.sh:

#! /bin/bash

python Desktop/school/secret_key.py

And here's where i got stuck, find_key.py:

import subprocess

program = subprocess.Popen("./program.sh")

now I could't find a way to send secret_key.py the input it asks for.

Is there anyway I can send a string input to secret_key.py from find_key.py?

Upvotes: 0

Views: 2143

Answers (1)

creichen
creichen

Reputation: 1768

To send input to and read output from a process opened via Popen, you can read from and write to the process using the process' stdin and stdout fields. You do need to tell Popen to set up pipes, though:

process = subprocess.Popen([SPIM_BIN] + extra_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
pin = process.stdin
pout = process.stdout

And now you can write to pin and read from pout as you would with any old file descriptor.

Note that this will probably not allow you to connect to the gnome-terminal. But it will allow you to connect to program.sh.

Upvotes: 1

Related Questions