Skip to content

Instantly share code, notes, and snippets.

@Reedbeta
Created June 27, 2020 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Reedbeta/74c72aa850acfc7d3d1efad18d2e287f to your computer and use it in GitHub Desktop.
Save Reedbeta/74c72aa850acfc7d3d1efad18d2e287f to your computer and use it in GitHub Desktop.
Generate code into a source file using python
# 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