How do I pause/resume a Python script?

Jeff Widman picture Jeff Widman · Oct 26, 2013 · Viewed 7.3k times · Source

I run python scripts on my macbook air that process data from external API's and often take several hours or occasionally even days.

However, sometimes I need to suspend my laptop in the middle of running a script so I can go to work or go home or similar.

How can I simply pause/resume these scripts in the middle of their for loops?

Is there something very simple that I can add at the script level that just listens for a particular key stroke to stop/start? Or something I can do at the *nix process management level?

I'm well aware of Pickle but I'd rather not deal with the hassle of serializing/unserializing my data--since all I'm doing is hibernating the mac, I'm hoping if the script gets paused and then I hibernate, that OS X will handle saving the RAM to disk and then restoring back to RAM when I reopen the computer. At that point, I can hit a simple keystroke to continue the python script.

Since I'm switching between different wifi networks, not sure if the different IPs will cause problems when my script tries to access the internet to reach the 3rd party APIs.

Answer

inspectorG4dget picture inspectorG4dget · Oct 26, 2013

This was originally a comment, but it seems to be what OP wants, so I'm reposting it as an answer

I would use ctrl+z to suspend your live, running process. This will leave you with a PID, which you can later resume with a call to fg: fg <job-number>.
This shouldn't have any implications with changed network settings (like IP, etc), at least as far as python is concerned. I can't speak to whether the API will freak out, though