I am trying to read a file as follows and I want to log an error if the file does not exist. So I wrote the following code. But this code does not go into the except block at all. I don't have the file for sure.
DEFAULT_ROLE_PROPERTIES = '/tmp/role.properties'
try:
self.role_properties = os.environ.get('VAULT_ROLE_PROPERTIES', DEFAULT_ROLE_PROPERTIES)
with open(self.role_properties, 'r') as rolefp:
cfg.readfp(rolefp)
self.role_id = cfg.get('region', 'role_id')
except Exception as msg:
self.log.error("Unable to read role properties")
I am not sure what is wrong with the syntax here. The above code is in an init function (constructor) could that be the issue?
ls /tmp/role.properties
ls: cannot access /tmp/role.properties: No such file or directory
You could use os.path to check that the path exists (first) before proceeding with getting environment/other attributes
Sample code:
If you were checking to see if a particular file was present, and valid (not empty) you could use os.stat
Hope this helps