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

Getting ready

We will produce a script, called  cron.py:

import argparse
import sys
from datetime import datetime
import configparser


def main(number, other_number, output):
result = number * other_number
print(f'[{datetime.utcnow().isoformat()}] The result is {result}',
file=output)


if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--config', '-c', type=argparse.FileType('r'),
help='config file',
default='/etc/automate.ini')
parser.add_argument('-o', dest='output', type=argparse.FileType('a'),
help='output file',
default=sys.stdout)

args = parser.parse_args()
if args.config:
config = configparser.ConfigParser()
config.read_file(args.config)
# Transforming values into integers
args.n1 = int(config['DEFAULT']['n1'])
args.n2 = int(config['DEFAULT']['n2'])

main(args.n1, args.n2, args.output)

Note the following details:

  1. The config file, is by default, /etc/automate.ini. Reuse config.ini from the previous recipe.
  2. A timestamp has been added to the output. This will make it explicit when the task is run.
  3. The result is being added to the file, as shown with the 'a' mode where the file is open.
  4. The ArgumentDefaultsHelpFormatter parameter automatically adds information about default values when printing the help using the -h argument.

Check that the task is producing the expected result and that you can log to a known file:

$ python3 cron.py
[2018-05-15 22:22:31.436912] The result is 35
$ python3 cron.py -o /path/automate.log
$ cat /path/automate.log
[2018-05-15 22:28:08.833272] The result is 35