Skip to content

Instantly share code, notes, and snippets.

@kms70847
Created March 12, 2019 17:37
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 kms70847/e99643dd989cbadab38e80821dbc639b to your computer and use it in GitHub Desktop.
Save kms70847/e99643dd989cbadab38e80821dbc639b to your computer and use it in GitHub Desktop.
#create_sample_directory.py - create some folders and files to demonstrate relative path includes
import os
os.mkdir("sample")
os.mkdir("sample/subfolder1")
os.mkdir("sample/subfolder2")
files = {
"sample/a.txt": """\
I've got a lovely bunch of coconuts
#include subfolder1/b.txt
That's what the showman said
""",
"sample/subfolder1/b.txt": """\
There they are, all standing in a row
#include ../subfolder2/c.txt
Give them a twist a flick of the wrist
""",
"sample/subfolder2/c.txt": """\
Big ones, small ones, some as big as your head
"""
}
for filename, contents in files.items():
with open(filename, "w") as file:
file.write(contents)
#main.py - performs relative-path includes on files
import sys
import re
import os
def include(filename, seen=()):
if filename in seen:
raise Exception("Possible circular import:", next_filename)
result = []
curpath = os.path.abspath(os.path.split(filename)[0])
with open(filename) as file:
for line in file:
if line.startswith("#include"):
next_filename = re.match(r"\#include (.*)", line).group(1)
next_filename = os.path.join(curpath, next_filename)
result.append(include(next_filename, seen + (filename,)))
else:
result.append(line)
return "".join(result)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Please provide a filename.")
sys.exit(0)
filename = sys.argv[1]
print(include(filename))
c:\Users\Kevin\Desktop\import_project>create_sample_directory.py
c:\Users\Kevin\Desktop\import_project>main.py sample/a.txt
I've got a lovely bunch of coconuts
There they are, all standing in a row
Big ones, small ones, some as big as your head
Give them a twist a flick of the wrist
That's what the showman said
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment