Dataloader execution freezes

Hello guys,
when I run the following script, it is executed till to the print(“just before for loop”) command and after it “freezes” (nothing prints in terminal)

import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

batch_size = 4

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
                                          shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
                                         shuffle=False, num_workers=2)


print("just before for loop")

for data in trainloader:    
    print(data)

print("Script run succesfully")

I waited 10 mins but nothing happened

Then I tried to run the script without the for loop and it executed perfectly. After it was completed I run the for loop from terminal and it also executed.
It seems to be executed perfectly when I run them separately but it “freezes” when they are in the same script.
I run pytorch to:

  • Windows
  • Conda 23.7.4
  • Python 3.11.5
  • Cuda 11.8
  • Spyder 5.4.3

Any suggestions??