【问题标题】:How to sequentially process multiple stdin inputs to python?如何顺序处理多个标准输入到python?
【发布时间】:2021-01-19 06:08:25
【问题描述】:

我有一个定期打印到标准输出的进程(以秒为单位),我想通过标准输入将该进程的输出通过管道传输到 python 程序来处理它。我面临的问题是,在继续之前,我还想听取用户关于如何处理它的意见。作为一个玩具示例,

定期打印到标准输出的程序 (interval.sh)。:

#!/bin/bash

for i in {1..10}
do
    echo $i
    sleep 1s
done

Python 程序 (test.py) 处理输入:

#!/usr/bin/env python3

import sys

for line in sys.stdin:
    while True:
        validate = input("Do you want to accept task {}? [y/n]\n".format(line))
        if validate == 'y':
            print("User accepted the input\n")
            break
        elif validate == 'n':
            print("User rejected the input\n")
            break
        else:
            print("Please enter a valid input")

我目前运行的程序如下:

$ ./interval.sh | ./test.py
Do you want to accept task 1
? [y/n]
Input not supported
Do you want to accept task 1
? [y/n]
Input not supported
Do you want to accept task 1
? [y/n]

如你所见,上面的程序认为来自shellcode的输入就是用户的输入。我想做的是:

$./interval.sh | ./test.py
Do you want to accept task 1? [y/n] y
The User accepted the input
Do you want to accept task 2? [y/n] y // Move to task 2 only when the user provides a valid input
The User accepted the input
Do you want to accept task 3? [y/n]

我看到了问题,因为来自程序和用户的输入来自标准输入,因此难以区分。此外,interval.sh 在我的实际场景中无法修改。我还能如何解决这个问题?

【问题讨论】:

  • 我建议从 python(子进程)中运行你的 shell 脚本并在你的代码中读取它的输出。这样,您发送的任何输入都将由 python 而不是首先由脚本处理(您可以选择是否将其发送到脚本)stackoverflow.com/questions/4760215/…
  • 似乎子进程会等到脚本完成完整执行。我是否能够在脚本打印出来并一个接一个地处理它时读取它的输出?
  • 子进程是否使用上述方法阻止您的代码?我相信应该有一种方法可以使它成为非阻塞的。将不得不查找它
  • 是的。它首先打印 1 到 10,然后继续询问用户输入。

标签: python


【解决方案1】:

这很可能与您使用管道的方式有关。 command_1 | command_2command_1 的输出充当 command_2 的输入,这就是您的程序失败的原因。

一个很好的选择是用python编写整个。

你可以尝试的另一件事是

for i in {1..10}
do
    echo $i
    sleep 1s
    ./test.py $i
done

通过对 bash 脚本的这一更改,您不再需要使用管道方法。简单地运行 bash 脚本会导致 python 程序每次都运行,因此 bash 代码被执行,它也可以解决输入问题。

import sys

line = sys.stdIn    

while True:
    validate = input("Do you want to accept task {}? [y/n]\n".format(line))
    if validate == 'y':
        print("User accepted the input\n")
        break
    elif validate == 'n':
        print("User rejected the input\n")
        break
    else:
        print("Please enter a valid input")

现在你可以运行 bash 脚本了

./interval.sh

【讨论】:

  • 谢谢! interval.sh 只是一个玩具示例。在我的场景中,我真的无法控制该程序。我将编辑我的问题以添加该信息。
猜你喜欢
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 2022-07-10
  • 2013-06-13
  • 1970-01-01
相关资源
最近更新 更多