【问题标题】:Feed python output to whiptail将 python 输出提供给whiptail
【发布时间】:2017-12-21 11:50:00
【问题描述】:

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

data-gen.sh

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

$ ./data-gen.sh | Whittail --title "TEST" --gauge "GAUGE" 0 50 0

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


现在我尝试从 python 复制同样的东西:

data-gen.py

#!/usr/bin/python
import time

print 10
time.sleep(1)
...
...
print 100
time.sleep(1)

$ ./data-gen.py | Whittail --title "TEST" --gauge "GAUGE" 0 50 0

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

任何想法如何让 python 输出成功地通过管道传输到whiptail?我没有用对话框尝试过这个;因为我想坚持使用大多数 ubuntu 发行版上预装的whiptail。

【问题讨论】:

  • 值得将print 20; time.sleep(1) 添加到python 脚本。在我的机器上data-gen.sh 使进度条逐渐移动,但data-gen.py 使它立即从 0 跳到 100。
  • 试试unbuffer ./data-gen.py | whiptail --title "TEST" --gauge "GAUGE" 0 50 0
  • python -u ./data-gen.py | whiptail --title "TEST" --gauge "GAUGE" 0 50 0
  • 谢谢 Arkadiusz .. python -u ./data-gen.py |鞭尾……工作得很好。无论如何要从 python 代码本身中执行此 unbuffer 输出?
  • 我将命令转换为答案。你可以在 shebang 中使用-u

标签: python linux bash dialog whiptail


【解决方案1】:

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
    
  • 修改data-gen.py的shebang:

    #!/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
    

【讨论】:

  • 做了#!/usr/bin/python -u 修改。效果很好!!不知何故,unbuffer 在我在 virtualbox 中运行的 ubuntu 16.04 上不起作用。每次打印后手动冲洗似乎有点痛苦。由于 -u 工作正常,我会继续这样做。
  • 你可以为此创建一个包装函数。
  • 是的,我可以创建一个包装器。但是使用 -u 标志有缺点吗?
  • 缺点是您只能在 shebang 行中添加一个选项,但您始终可以通过连接 -us 等选项来避免这种情况。
  • 好消息。再次感谢。这是我第一次遇到需要添加 shebang line 选项。
猜你喜欢
  • 2017-09-09
  • 2012-04-06
  • 1970-01-01
  • 2019-01-03
  • 2021-05-19
  • 2016-05-02
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多