Created
November 22, 2024 00:43
-
-
Save rickwierenga/e5f776776c876508f6f772cae2366705 to your computer and use it in GitHub Desktop.
convert.py
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 sys | |
def indent_code(code, spaces=2): | |
"""Indents each line of the provided code.""" | |
indentation = " " * spaces | |
return "\n".join(f"{indentation}{line}" if line.strip() else line for line in code.splitlines()) | |
def wrap_in_async_main(file_path): | |
"""Reads a file, wraps its content in an async def main() block, and appends the if __name__ == '__main__' block.""" | |
try: | |
with open(file_path, "r") as f: | |
content = f.read() | |
# Indent the content | |
indented_content = indent_code(content) | |
# Wrap in async main and add if __name__ block | |
wrapped_content = ( | |
f"async def main():\n" | |
f"{indented_content}\n\n" | |
f"if __name__ == \"__main__\":\n" | |
f" import asyncio\n" | |
f" asyncio.run(main())\n" | |
) | |
return wrapped_content | |
except FileNotFoundError: | |
print(f"Error: File '{file_path}' not found.") | |
sys.exit(1) | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: python convert.py <file.py>") | |
sys.exit(1) | |
input_file = sys.argv[1] | |
output_file = "wrapped_" + input_file | |
# Generate the wrapped content | |
wrapped_content = wrap_in_async_main(input_file) | |
# Write to a new file | |
with open(output_file, "w") as f: | |
f.write(wrapped_content) | |
print(f"Wrapped file created: {output_file}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment