Home > Enterprise >  read-while loop with variables in bash -- equivalent in Python?
read-while loop with variables in bash -- equivalent in Python?

Time:05-11

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

CodePudding user response:

The bash script reads each line from standard input, splits it into words, and assigns the words to var1, var2, and var3in order. It loops untilread` returns an error, which normally happens at EOF.

The roughly equivalent python code would be:

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

maxsplit=3 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.

  • Related