从管道bash脚本运行时Python脚本不等待用户输入

2 投票
1 回答
1219 浏览
提问于 2025-04-20 21:58

我正在用一个很酷的命令行构建一个交互式安装程序:

curl -L http://install.example.com | bash

这个bash脚本会快速调用一个python脚本:

# file: install.sh
[...]
echo "-=- Welcome -=-"
[...]
/usr/bin/env python3 deploy_p3k.py

然后这个python脚本会提示用户输入:

# file: deploy_py3k.py
[...]
input('====> Confirm or enter installation directory [/srv/vhosts/project]: ')
[...]
input('====> Confirm installation [y/n]: ')
[...]

问题:因为这个python脚本是从一个bash脚本中运行的,而这个bash脚本又是通过curl命令传输过来的,所以当提示出现时,它会自动“跳过”,结果就变成这样:

$ curl -L http://install.example.com | bash
-=- Welcome ! -=-
We have detected you have python3 installed.
====> Confirm or enter installation directory [/srv/vhosts/project]: ====> Confirm installation [y/n]: Installation aborted.

正如你所看到的,脚本并没有等待用户输入,因为输入被绑定到了curl的输出上。因此,我们面临以下问题:

curl [STDOUT]=>[STDIN] BASH (which executes python script)
= the [STDIN] of the python script is the [STDOUT] of curl (which contains at a EOF) !

我该如何保持这个非常有用且简短的命令行(curl -L http://install.example.com | bash),同时还能提示用户输入呢?我应该以某种方式将python的标准输入从curl中分离出来,但我找不到方法。

非常感谢你的帮助!

我还尝试过的事情

  • 在子shell中启动python脚本:$(/usr/bin/env python3 deploy.py)

1 个回答

2

你可以随时从控制终端(tty)重定向标准输入,前提是有一个控制终端:

/usr/bin/env python3 deploy_p3k.py < /dev/tty

或者

/usr/bin/env python3 deploy_p3k.py <&1

撰写回答