代码之家  ›  专栏  ›  技术社区  ›  dzen

python结构:如何回答键盘输入?

  •  23
  • dzen  · 技术社区  · 15 年前

    我想自动化一些程序提示的问题的响应,比如mysql提示输入密码,或者apt请求“是”或…当我想用./manage.py rebuild_index重建我的草堆索引时。

    对于MySQL,我可以使用--password=switch,我确信apt有一个类似“安静”的选项。但是我如何才能将响应传递给其他程序呢?

    6 回复  |  直到 7 年前
        1
  •  13
  •   Esteban Küber    15 年前

    为什么你不能只用 pipes ?

    例如,对于自动接受,只需使用 yes ,只会输出 y .

    yes | rm *.txt
    

    http://upload.wikimedia.org/wikipedia/en/thumb/f/f6/Pipeline.svg/280px-Pipeline.svg.png

        2
  •  36
  •   buckley    15 年前

    如果要查找用户以确认操作,请使用confrim方法。

    if fabric.contrib.console.confirm("You tests failed do you want to continue?"):
      #continue processing
    

    或者,如果您正在寻找从用户那里获取输入的方法,请使用prompt方法。

    password = fabric.operations.prompt("What is your password?")
    
        3
  •  1
  •   dzen    15 年前

    这两种方法都有效。

    我选择第一个,因为我不想与我的部署系统进行任何交互。

    下面是我使用的解决方案:

    % yes | ./manage.py rebuild_index

    警告:这将不可避免地从搜索索引中删除所有内容。 在此之后,您的选择是从备份中还原,或通过 rebuild_index 命令。 您确定要继续吗?[y/n] 删除索引中的所有文档,因为您说过。 已删除所有文档。 索引27个项目。

        4
  •  1
  •   akv    14 年前

    Fabric(1.0a)的开发版本现在支持与远程程序的交互。 http://docs.fabfile.org/1.0a/usage/interactivity.html

        5
  •  0
  •   luoluo    7 年前

    回答晚了,但希望这能帮助有类似问题的人。

    不同点:

    1. 回答 两个或更多不同的输入 到控制台。
    2. parallel mode 支持。
    3. 任何类型的输入 yes/no/y/n 包括。

    问题

    [hostxxx] out: Type 'c' if you want to use the Commercial Edition.
    [hostxxx] out: Type 'o' if you want to use the Open Source Edition.
    [hostxxx] out: Type '3' to view the GNU General Public License version 3.
    [hostxxx] out: Type 'L' to view the Lesser GNU General Public License version 2.1.
    [hostxxx] out: Type 'yes' to accept this license offer.
    [hostxxx] out: Type 'no' to decline this license offer.
    

    解决方案:

    使用 printf 而不是 yes 为了增加灵活性,同时这就像一个魅力 parallel 模式。

    @parallel
    def demo_multi_input():
        run('printf "o\nyes\n"|./configure --prefix=/home/work/bin/qt')
    
        6
  •  -1
  •   Robert Columbia yusuf dalal    8 年前

    使用此代码:

    run("echo yes|./manage.py rebuild_index")