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

标签 python ubuntu subprocess

我制作了一个检查 key 的程序。和另一个应该找到 key 的程序。我设法在第二个程序中打开了一个子进程,但无法向它发送输入。这是检查 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()

现在我制作了一个 .sh 文件,以便能够在新终端中作为子进程运行它,program.sh :
#! /bin/bash

python Desktop/school/secret_key.py

这就是我卡住的地方,find_key.py :
import subprocess

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

现在我找不到发送secret_key.py 的方法它要求的输入。

无论如何我可以将字符串输入发送到 secret_key.py来自 find_key.py ?

最佳答案

要向通过 Popen 打开的进程发送输入和读取输出,您可以使用进程'stdin 读取和写入进程。和 stdout字段。您确实需要告诉 Popen但是要设置管道:

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

现在你可以写信给 pin并从 pout 中读取就像使用任何旧文件描述符一样。

请注意,这可能不允许您连接到 gnome-terminal。 .但它将允许您连接到 program.sh .

关于Python子进程,给子进程一个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20210717/

相关文章:

python - 导入时文件名冲突

python - 有什么官方方法可以获取模型的管理选项吗?

python - BLAS/LAPACK 未安装 : How to install it?

Python 子进程 Popen : Why does "ls *.txt" not work?

python - 从压缩文件中读取 matlab 文件 (*.mat) 而无需解压缩到 Python 中的目录

python - 有没有办法让Python Turtle中的一个对象与另一个对象一起旋转?

java - 类文件未被读取

python - 如何在 ubuntu 上为 python ML 安装软件包?

python - 无法使用 subprocess.Popen 捕获 ls -la 的结果

python2.7 使用调试的行为与不使用调试的行为不同