Script runs on terminal but not from Scheduler

Wrong. It only works if print command has previously been issued in the same console session (and in the same context), and is expected to fail otherwise. The print command [temporarily] assigns these numbers to each entry. This has recently been explained in this thread.