简体   繁体   中英

read-while loop with variables in bash -- equivalent in Python?

Currently refactoring some old code and looking to convert some bash scripts to python.

We have a small piece of functionality written in bash that's similar to:

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.

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.

Lastly, I'm looking to convert this functionality into 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.

Can give more context around the logic in the while loop if required :)

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 in order. It loops until read` returns an error, which normally happens at EOF.

The roughly equivalent python code would be:

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

maxsplit=2 will make split() return at most 3 values. If the input has more than 3 words, all the remaining words will be included in the last word. This is similar to how read works when there are more input words than variables.

The Python version won't work if less than 3 words are typed. bash will assign an empty string to remaining variables, Python will report an error. There are ways to recode this to solve this problem if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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