首页 > 解决方案 > Python3 在 subprocess.call 之后写入控制台

问题描述

我正在用 Python3 编写一个脚本,该脚本进行 subprocess.call,并且该调用要求用户输入密码。我希望脚本调用子进程,然后自动写入密码,但到目前为止我还没有成功。如果有帮助,我正在从 Linux 机器上执行它。

我试过 Popen 和 Pipe

p = Popen("Command that when executed requires me to input a password", shell=True, stdin=PIPE) p.stdin.write(PASSWORD.encode("UTF-8"))

这给出了一个错误,指出无法读取密码(这意味着至少它完成了该过程)

以及正常的 subprocess.call

subprocess.call(COMMAND) sys.stdin.write(PASSWORD)

在这种情况下,它会一直等到我按 ENTER 键,然后执行下一行。

标签: pythonbashsubprocessstdin

解决方案


尝试:

p1 = subprocess.Popen(['echo','PASSWORD'], stdout=PIPE)
subprocess.Popen("Command that when executed requires me to input a password", stdin=p1.stdout)
p1.stdout.close()

首先,您将某些内容回显到管道,该内容用作第二个子进程的输入


推荐阅读