I have a sample YAML file and I'm unable to parse it using PyYAML library.
setup.yml
:
key: HostName
deviceid: port1
Python code
with open('../configs/setup.yml') as stream:
try:
print 'yaml.data ==', yaml.load(stream)
print 'yaml.data ==', type(yaml.load(stream))
# print 'yaml.data ==', dict(yaml.load(stream))
data = yaml.safe_load(stream)
self.device_id = data['deviceid']
self.key = yaml.load(stream)['key']
except yaml.YAMLError as exc:
print(exc)
The yaml.load(stream)
type is Nonetype
, I thought it should be a dictionary.
After you read the stream with the first load()
there is no more data in the stream and the next load returns None
and doesn't throw an Error (e.g. end of stream)..
What you could do is:
import yaml
with open('../configs/setup.yml') as stream:
print 'yaml.data ==', yaml.load(stream)
stream.seek(0, 0)
print 'yaml.data ==', type(yaml.load(stream))
# print 'yaml.data ==', dict(yaml.load(stream))
with open('../configs/setup.yml') as stream:
data = yaml.safe_load(stream)
device_id = data['deviceid']
key = data['key']
or just store the loaded document in data from the start. I removed the reference to self.
because of the previous errors, you never came to that undefined variable.
However, there is almost never a need to use PyYAML's load()
(and that is certainly true here) it is unsafe and doesn't warn you about that. With uncontrolled data it can wipe your disc, or worse.