将python输出到whiptail

问题描述 投票:1回答:1

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

data-跟.是

#!/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中复制相同的东西:

data-跟.朋友

#!/usr/bin/python
import time

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

$ ./data-gen.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。

python linux bash dialog whiptail
1个回答
1
投票

man whiptail说:

--gauge文本高度宽度百分比

          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.

这意味着whiptailstandard 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之后手动冲洗stdout: #!/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
© www.soinside.com 2019 - 2024. All rights reserved.