Pregunta

I liked the idea of Literate CoffeeScript and wanted to see if I could get something working with Python. I tried to accomplish something similar to this simple Literate Ruby and ended up with the following. The program takes Literate Python in standard input, a file, or list of files and executes just the code.

import fileinput
import re

code = ''

for line in fileinput.input():
    match = re.match(r'([ ]{4}|\t)(.*)', line)
    if match:
        code += match.group(2) + '\n'

exec code

A simple Literate Python file.

# Python Hello World Program

A simple example of a Literate Python Hello Word program.

    print "hello world"

I'm new to Python and wanted to know if I'm missing something or if there is a better solution.

¿Fue útil?

Solución

As I said in a comment, eval or exec are evil, a better alternative is to use the code module as in the following example. Also, you may prefer to compile the regex, in order to only perform the matching at each iteration over the input instead of building the automaton at each iteration.

import fileinput

import code
console = code.InteractiveConsole(locals())

import re    
r = re.compile(r'([ ]{4}|\t)(.*)')

code = ''

for line in fileinput.input():
    match = r.match(line)
    if match:
        console.push(match.group(2))

Though that example will output the results on sys.stdout so you may want to use instead an overloaded class such as the one in this example.

Otros consejos

Combing python and markdown-like syntax is best done using tools rather than changing the language. For example:

  • sphinx (render output from restructured text in doc strings or other files, both of which may have embedded code samples)
  • ipython notebook (a combination of "cells" with either markdown or python code)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top