Created
June 27, 2020 16:55
-
-
Save Reedbeta/74c72aa850acfc7d3d1efad18d2e287f to your computer and use it in GitHub Desktop.
Generate code into a source file using python
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
# Load the source file | |
sourcePath = r'c:\path\to\my\file.cpp' | |
sourceText = codecs.open(sourcePath, encoding='utf-8').read() | |
# Find the generated section | |
startMarker = ( | |
'''/* | |
* Generated data tables - do not edit by hand! | |
* To regenerate, run my_fancy_script.py. | |
*/ | |
''') | |
startMarkerPos = sourceText.index(startMarker) | |
endMarker = ( | |
'''/* | |
* End of generated section | |
*/ | |
''') | |
endMarkerPos = sourceText.index(endMarker) | |
# Rewrite the file with the new generated section, | |
# but only if it's different from the existing one. | |
generatedCodePrev = sourceText[startMarkerPos + len(startMarker) : endMarkerPos] | |
if generatedCode != generatedCodePrev: | |
sourceTextNew = (sourceText[:startMarkerPos] + | |
startMarker + | |
generatedCode + | |
sourceText[endMarkerPos:]) | |
codecs.open(sourcePath, mode='w', encoding='utf-8').write(sourceTextNew) | |
print('Updated %s with new data tables.' % sourcePath) | |
else: | |
print('No changes to %s needed.' % sourcePath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment