Forum Archive

Syntax-highlight Python code on screen while running

Obelisk

1.How to get Syntax-highlight Python code on screen while running, e.g. this:

import random
print 'hello'
print random.randint(42)

will turn into this Syntax-highlight Python code on screen while running?

Another questions:

  1. Is it possible to control(copy&paste ect) editor with code's function?

  2. How to read a .py file into a string or list?

ccc

I do not understand your question on syntax highlighting however, random.randint() required two parameters, not just one.

For the other questions...

The clipboard module enables your scripts to copy and paste and the editor module enables them to get and set Editor content.

with open('python_code.py') as in_file:
    python_code = in_file.read()  # copies file contents to a str
Obelisk

Many thanks. I mean markdown example, is there any simple method to get syntax hightlight like this:

```python
print 'hello'
```
JonB

i think you may need to be a little more descriptive... tell us what you are trying to achieve.

  • do you want the html source code of syntax highlighted Python?
  • or, you want to display highlighted Python within pythonista, but outside of the editor?
  • do you want this "on screen" as in in the console, or in a window?
  • when you say while running, do you mean you are trying to debug code, and would like a highlighted line source debugger?
Obelisk

The first three issues, my answers are yes, which method is the simplest? how to make it? Thanks a lot.

omz

Here's an example for showing syntax-highlighted code (that is in the clipboard):

import ui
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from pygments.styles import get_style_by_name
import clipboard

# Syntax-highlight code in clipboard:
code = clipboard.get()
html_formatter = HtmlFormatter(style='colorful')
highlighted_code = highlight(code, PythonLexer(), html_formatter)
styles = html_formatter.get_style_defs()
html = '<html><head><style>%s</style></head><body>%s</body></html>' % (styles, highlighted_code)

# Present result in a WebView:
webview = ui.WebView(frame=(0, 0, 500, 500))
webview.scales_page_to_fit = False
webview.load_html(html)
webview.present('sheet')
Obelisk

A thousand thanks.