将python输出提供给whiptai

2024-05-15 07:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

数据-上海通用汽车

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

$/数据-上海通用汽车|鞭梢--标题“测试”--量规“gauge”0 50 0

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

Whiptail working when piping output from shell script


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

数据-发电机

^{pr2}$

$/数据-发电机|鞭梢--标题“测试”--量规“gauge”0 50 0

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

No change in progress bar when piping python output

有什么办法让python输出成功地通过管道传输到whiptail?我没有尝试过dialog;因为我想坚持whiptail,它是预装在大多数ubuntu发行版上的。在


Tags: 数据进度条echo服务器标题管道linuxsleep
1条回答
网友
1楼 · 发布于 2024-05-15 07:38:43

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读取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之后手动刷新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
    

相关问题 更多 >