Created
January 29, 2020 09:57
-
-
Save tarnacious/bab72eadb0cb141390af899b8cd95f77 to your computer and use it in GitHub Desktop.
scan comments in pyyaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yaml | |
from yaml.composer import Composer | |
from yaml.reader import Reader | |
from yaml.scanner import Scanner | |
from yaml.parser import Parser | |
from yaml.constructor import SafeConstructor | |
from yaml.resolver import Resolver | |
class CommentsScanner(Scanner): | |
def scan_to_next_token(self): | |
if self.index == 0 and self.peek() == '\uFEFF': | |
self.forward() | |
found = False | |
while not found: | |
while self.peek() == ' ': | |
self.forward() | |
if self.peek() == '#': | |
comment = '' | |
while self.peek() not in u'\0\r\n\x85\u2028\u2029': | |
comment += self.peek() | |
self.forward() | |
self.comments.append(comment) | |
if self.scan_line_break(): | |
if not self.flow_level: | |
self.allow_simple_key = True | |
else: | |
found = True | |
class CommentLoader(Reader, CommentsScanner, Parser, Composer, SafeConstructor, Resolver): | |
def __init__(self, stream): | |
self.comments = [] | |
Reader.__init__(self, stream) | |
Scanner.__init__(self) | |
Parser.__init__(self) | |
Composer.__init__(self) | |
SafeConstructor.__init__(self) | |
Resolver.__init__(self) | |
content = "prop: value # comment" | |
loader = CommentLoader(content) | |
loader.get_single_data() | |
print(loader.comments) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[u'# comment'] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PyYAML==5.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment