【问题标题】:Python script not waiting for user input when ran from piped bash script从管道 bash 脚本运行时,Python 脚本不等待用户输入
【发布时间】:2014-09-10 15:25:20
【问题描述】:

我正在使用漂亮的命令行构建交互式安装程序:

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 脚本运行的,它本身是来自 curl 的 piped,所以当提示出现时,它会自动“跳过”并且一切都像这样结束:

$ 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)

【问题讨论】:

    标签: python linux bash pipe


    【解决方案1】:

    你总是可以从控制 tty 重定向标准输入,假设有一个:

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

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

    【讨论】:

    • 为什么要将STDERR 重定向到STDOUT(与2&gt;&amp;1)?
    • 为了完整起见。从您的描述中我无法判断它们是否已被重定向和/或 python 脚本是否需要它们。无论如何,您的具体问题的关键是&lt; /dev/tty
    • 是的,&lt; /dev/tty 就足够了。非常感谢!
    • FWIW,另一种解决方案是/usr/bin/env python3 deploy_p3k.py &lt;&amp;1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 2016-04-10
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多