There is a built-in command line utility caffeinate
that can be used to prevent macOS from sleeping.
To prevent macOS from sleeping before a process with given PID exits:
$ caffeinate -w PID
To prevent macOS from sleeping for the next N seconds:
$ caffeinate -t N