代码之家  ›  专栏  ›  技术社区  ›  G.A.

将python输出馈送到whiptail

  •  1
  • G.A.  · 技术社区  · 7 年前

    我希望通过将一些PYTHON代码的输出传递给“whiptail”,在无头linux服务器上使用TUI(文本用户界面)。不幸的是,whiptail似乎什么也没发生。当我通过管道从正则shell脚本输出时,whiptail工作正常。以下是我所拥有的:

    数据-gen.sh

    #!/bin/bash
    echo 10
    sleep 1
    echo 20
    sleep 1
    ...
    ...
    echo 100
    sleep 1
    

    $ ./data-gen.sh | whiptail--标题“测试”--量规“量规”0 50 0

    下面的进度条按预期递增。

    Whiptail working when piping output from shell script


    现在,我尝试从python复制同样的内容:

    数据-gen.py

    #!/usr/bin/python
    import time
    
    print 10
    time.sleep(1)
    ...
    ...
    print 100
    time.sleep(1)
    

    $ ./data-gen.py | whiptail--标题“测试”--量规“量规”0 50 0

    我得到下面的进度条保持在0%。未看到增量。一旦后台的python程序退出,Whiptail就会退出。

    No change in progress bar when piping python output

    有没有办法让python输出成功地通过管道传输到whiptail?我没有用dialog尝试过这一点;因为我想坚持使用大多数ubuntu发行版上预装的whiptail。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Arkadiusz Drabczyk    7 年前

    man whiptail 说:

    --仪表文本高度宽度百分比

              A gauge box displays a meter along the bottom of the
              box.  The meter indicates a percentage.  New percentages
              are read from standard input, one integer per line.  The
              meter is updated to reflect each new percentage.  If
              stdin is XXX, the first following line is a percentage
              and subsequent lines up to another XXX are used for a
              new prompt.  The gauge exits when EOF is reached on
              stdin.
    

    这意味着 whiptail 读取自 standard input . 许多程序 通常在输出不到文件时缓冲输出。强制 python 要产生无缓冲输出,您可以:

    • 使用运行它 unbuffer :

      $ unbuffer ./data-gen.py | whiptail --title "TEST" --gauge "GAUGE" 0 50 0
      
    • 使用 -u 打开命令行:

      $ python -u ./data-gen.py | whiptail --title "TEST" --gauge "GAUGE" 0 50 0
      
    • 修改的shebang data-gen.py :

      #!/usr/bin/python -u
      import time
      print 10
      time.sleep(1)
      print 20
      time.sleep(1)
      print 100
      time.sleep(1)
      
    • 每次之后手动冲洗标准液 print :

      #!/usr/bin/python
      import time
      import sys
      
      print 10
      sys.stdout.flush()
      time.sleep(1)
      print 20
      sys.stdout.flush()
      time.sleep(1)
      print 100
      sys.stdout.flush()
      time.sleep(1)
      
    • 设置 PYTHONUNBUFFERED 环境变量:

      $ PYTHONUNBUFFERED=1 ./data-gen.py | whiptail --title "TEST" --gauge "GAUGE" 0 50 0