gpt4 book ai didi

python - 将 python 输出提供给 whiptail

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:36:54 25 4
gpt4 key购买 nike

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

数据生成.sh

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

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

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

Whiptail working when piping output from shell script


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

数据生成.py

#!/usr/bin/python
import time

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

$ ./数据生成.py | whiptail --title "TEST"--gauge "GAUGE"0 50 0

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

No change in progress bar when piping python output

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

最佳答案

man whiptail 说:

--gauge text height width percent

          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标准输入 读取。许多程序通常在不进入文件时缓冲输出。强制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)
  • 在每次打印后手动刷新标准输出:

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

关于python - 将 python 输出提供给 whiptail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com