简体   繁体   English

Python子进程,给子进程一个输入

[英]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.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 :现在我制作了一个 .sh 文件,以便能够在新终端中作为子进程program.sh运行它:

#! /bin/bash

python Desktop/school/secret_key.py

And here's where i got stuck, find_key.py :这就是我卡住的地方, 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.现在我找不到将其要求的输入发送给secret_key.py的方法。

Is there anyway I can send a string input to secret_key.py from find_key.py ?反正我有可以将字符串输入发送到secret_key.pyfind_key.py

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.要将输入发送到通过 Popen 打开的进程并从中读取输出,您可以使用进程的stdinstdout字段读取和写入进程。 You do need to tell Popen to set up pipes, though:不过,您确实需要告诉Popen设置管道:

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.现在您可以像使用任何旧文件描述符一样写入pin和读取pout

Note that this will probably not allow you to connect to the gnome-terminal .请注意,这可能不允许您连接到gnome-terminal But it will allow you to connect to program.sh .但它将允许您连接到program.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM