开发者

Formatting Python code for the web

开发者 https://www.devze.com 2023-03-29 07:12 出处:网络
Until recently, I posted Python code (whitespace matters) to blogspot.com using something like this: <div style=\"overflow-x: scroll \">

Until recently, I posted Python code (whitespace matters) to blogspot.com using something like this:

<div style="overflow-x: scroll "> 
<table bgcolor="#ffffb0" border="0" width="100%" padding="4"> 
<tbody><tr><td><pre style=" hidden;font-family:monaco;"> 
my code here 
</pre></table></div> 

About a week ago, the posts started acquiring additional newlines so all of this is double-spaced. Using a simple <pre> tag is no good (besides losing the color) b/c it also results in double newlines, while a <code> tag messes with the whitespace. I guess I could just add &nbsp;*4---but that's frowned upon or s开发者_如何转开发omething by the HTML style gods.

The standard answer to this (like right here on SO) is to get syntax coloring or highlighting through the use of css (which I don't know much about), for example as discussed in a previous SO question here. The problem I have with that is that all such solutions require loading of a resource from a server on the web. But if (say 5 years from now) that resource is gone, the html version of the code will not render at all. If I knew Javascript I guess I could probably fix that.

The coloring problem itself is trivial, it could be solved through use of <style> tags with various definitions. But parsing is hard; at least I've not made much progress trying to parse Python myself. Multi-line strings are a particular pain. I could just ignore the hard cases and code the simple ones.

TextMate has a command Create HTML from Document. The result is fairly wordy but could just be pasted into a post. But say if you had 3 code segments, then it's like 1000 lines or something. And of course it's a document, so you have to actually cut before you paste.

Is there a simple Python parser? A better solution?

UPDATE: I wrote my own parser for syntax highlighting. Still a little buggy perhaps, but it is quite simple and a self-contained solution. I posted it here. Pygments is also a good choice as well.


Why don't you use pygments?


What worked for me was to use prettify. At the top of the HTML, add the line

<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>

to auto-run prettify. Then use

<code class="prettify">
... enter your code here ...
</code>

in your HTML.

I actually used this code on blogspot.com; here is an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消