Skip to content

Instantly share code, notes, and snippets.

@estevaofon
Last active June 10, 2024 20:25
Show Gist options
  • Save estevaofon/66c5842a5a4733b4d6a58bc4c8e92bd0 to your computer and use it in GitHub Desktop.
Save estevaofon/66c5842a5a4733b4d6a58bc4c8e92bd0 to your computer and use it in GitHub Desktop.
import pygments
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import sys
def python_to_html(input_file, output_file):
# Read the Python code from the input file
with open(input_file, 'r', encoding='utf-8') as f:
code = f.read()
# Use Pygments to highlight the code
lexer = PythonLexer()
formatter = HtmlFormatter(nowrap=True)
highlighted_code = pygments.highlight(code, lexer, formatter)
# Write the highlighted code to the output file
with open(output_file, 'w', encoding='utf-8') as f:
f.write('<pre><span></span>') # Add the initial <pre><span></span> tags
f.write(highlighted_code)
f.write('</pre>') # Add the closing </pre> tag
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: python python_to_html.py <input_file.py> <output_file.html>")
else:
input_file = sys.argv[1]
output_file = sys.argv[2]
python_to_html(input_file, output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment