简体   繁体   English

bash中带有变量的read-while循环-在Python中等效吗?

[英]read-while loop with variables in bash -- equivalent in Python?

Currently refactoring some old code and looking to convert some bash scripts to python.目前正在重构一些旧代码并希望将一些 bash 脚本转换为 python。

We have a small piece of functionality written in bash that's similar to:我们有一小部分用 bash 编写的功能,类似于:

var1=$1
var2=$2
var3=$3

    while read var1 var2 var3; do
       logic

To be perfectly honest I'm not sure I understand what this is doing.老实说,我不确定我是否理解这是在做什么。 I've seen while read loops in the context of a file before, but I'm not sure what is happening here with these 3 variables instead of a file.我之前在文件的上下文中看到过 while read 循环,但我不确定这 3 个变量而不是文件在这里发生了什么。

I'd like to understand what exactly this while read is doing firstly but I haven't been able to find much resources online that explain this logic in the context of variables, all I'm seeing are while read loops that are iterating actual files.我想首先了解这 while read 到底在做什么,但我无法在网上找到很多资源来解释变量上下文中的这种逻辑,我所看到的只是 while read 循环正在迭代实际文件.

Lastly, I'm looking to convert this functionality into python.最后,我希望将此功能转换为 python。 Any suggestions for similar Python functionality would be appreciated (still new to python too) but hopefully if I can grasp the logic above first I should be able to find something myself.任何关于类似 Python 功能的建议都将不胜感激(对于 Python 来说还是新手),但希望如果我能首先掌握上面的逻辑,我应该能够自己找到一些东西。

Can give more context around the logic in the while loop if required :)如果需要,可以围绕 while 循环中的逻辑提供更多上下文:)

Any help would be grately appreciated任何帮助将不胜感激

The bash script reads each line from standard input, splits it into words, and assigns the words to var1 , var2, and var3 in order. It loops until bash脚本从标准输入读取每一行,将其拆分为单词,然后将单词按顺序分配给var1var2, and var3 in order. It loops until in order. It loops until read` returns an error, which normally happens at EOF. in order. It loops until read` 返回一个错误,这通常发生在 EOF。

The roughly equivalent python code would be:大致等效的python代码是:

while True:
    try:
        var1, var2, var3 = input().split(maxsplit=2)
    except EOFError:
        break
    # logic

maxsplit=2 will make split() return at most 3 values. maxsplit=2将使split()最多返回 3 个值。 If the input has more than 3 words, all the remaining words will be included in the last word.如果输入的单词超过 3 个,则所有剩余的单词都将包含在最后一个单词中。 This is similar to how read works when there are more input words than variables.这类似于输入单词多于变量时read的工作方式。

The Python version won't work if less than 3 words are typed.如果键入的单词少于 3 个,Python 版本将不起作用。 bash will assign an empty string to remaining variables, Python will report an error. bash会给剩余的变量分配一个空字符串,Python 会报错。 There are ways to recode this to solve this problem if necessary.如有必要,有一些方法可以重新编码以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM