Fix Python infinite loop bugs