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

How it works...

Note that the argparse module allows us to define files as parameters, with the argparse.FileType type, and opens them automatically. This is very handy, and will raise an error if the file is not valid.

Remember to open the file in the correct mode. In Step 5, the config file is opened in read mode ( r) and the output file in write mode ( w), which will overwrite the file if it exists. You may find the append mode ( a), which will add the next piece of data at the end of an existing file.

The configparser module allows us to use config files with ease. As demonstrated in Step 2, the parsing of the file is as simple as follows:

config = configparser.ConfigParser()
config.read_file(file)

The config will then be accessible as a dictionary divided by sections, and then values. Note that the values are always stored in string format, requiring to be transformed into other types, such as integers:

If you need to obtain boolean values, do not perform value = bool(config[raw_value]) as it will be transformed into True no matter what; for instance, the string False is a true string, as it's not empty. Use the .getboolean method instead, for example, value = config.getboolean(raw_value).

Python3 allows us to pass a file parameter to the print function, which will write to that file. Step 5 shows the usage to redirect all the printed information to a file. 

Note that the default parameter is sys.stdout, which will print the value to the Terminal (standard output). This makes it so that calling the script without an -o parameter will display the information on the screen, which is helpful in debugging:

$ python3 prepare_task_step5.py -c config.ini
The result is 35
$ python3 prepare_task_step5.py -c config.ini -o result.txt
$ cat result.txt
The result is 35