Python Automation Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Obtain the full path of the Python interpreter. This is the interpreter that's on your virtual environment:
$ which python
/your/path/.venv/bin/python
  1. Prepare the cron to be executed. Get the full path and check that it can be executed with no problem. Execute it a couple of times:
$ /your/path/.venv/bin/python /your/path/cron.py -o /path/automate.log
$ /your/path/.venv/bin/python /your/path/cron.py -o /path/automate.log

  1. Check that the result is being added correctly to the result file:
$ cat /path/automate.log
[2018-05-15 22:28:08.833272] The result is 35
[2018-05-15 22:28:10.510743] The result is 35
  1. Edit the crontab file to run the task once every five minutes:
$ crontab -e

*/5 * * * * /your/path/.venv/bin/python /your/path/cron.py -o /path/automate.log

Note that this opens an editing Terminal with your default command-line editor.

If you haven't set up your default command-line editor, by default, it is likely Vim. This can be disconcerting if you don't have experience with Vim. Press I to start inserting text and Esc when you're done. Then, exit after saving the file with :wq. For more information about Vim, see this introduction: https://null-byte.wonderhowto.com/how-to/intro-vim-unix-text-editor-every-hacker-should-be-familiar-with-0174674.
For information on how to change the default command-line editor, see the following: https://www.a2hosting.com/kb/developer-corner/linux/setting-the-default-text-editor-in-linux.
  1. Check the crontab contents. Note that this displays the crontab contents, but doesn't set it to edit:
$ contab -l
*/5 * * * * /your/path/.venv/bin/python /your/path/cron.py -o /path/automate.log
  1. Wait and check the result file to see how the task is being executed:
$ tail -F /path/automate.log
[2018-05-17 21:20:00.611540] The result is 35
[2018-05-17 21:25:01.174835] The result is 35
[2018-05-17 21:30:00.886452] The result is 35