Print non-unicode subscript to Python console - python

I'm using Python 3.10 to implement a classical mechanics problem, and I want to print a message to the console asking the user to input the initial velocities. I am using x, y, and z as coordinates so ideally I want to denote the velocity components as vx, vy, and vz.
Originally I thought of using unicode subscirpts, but apparently they don't exist for y and z (as this other SO answer explains).
Of course I could just display (v_x, v_y, v_z), but I wanted it to look a bit more polished. Is there an easy way to display non-unicode subscripts in Python? Or otherwise, some very bare-bones UI package where I can have more freedom in formatting the text (like using LaTeX, or Markdown)?

No -
The terminal emulator (or command line) can only display characters, and does not allow for unlimited character transformations, as it is possible with text on a web browser or in a graphic interface.
ALthough there are special character sequences that can trigger special features such as foreground and background color, underline and blinking, those have to be implemented by the terminal emulator program itself, and appart from a subset, there is no universal code convention. The closest one, are what we usually call "ANSI escape code sequences" do not provide for a subscript or super-script convert - you can check the available codes on wikipedia - those will work in most terminal programs for Linux and MacOS and most custom terminal programas in windows (including the one called "terminal" in the microsoft store), but not on the default "cmd" app which cames pre-installed in windows.
(There is a Python package called "colorama" which tries to overcome this limitation to cmd, allowing cross-platform terminal programs able to display rich text - but it will filter out the codes for using fullcolor in terminal programs that accept them, so it is not always a good idea)
All that said, the tables as they are in the linked wikepdia article may be a bit confusing - but for shorten: "CSI" is the sequence "\x1b[" - where "\x1b"is the "ESC" character (decimal 27) , and "[" is a literal "open square bracket" char - the "SGR" sequence is"\x1b[<list-of-parameters-separated-by-;>m"` (again, "m" here is just the plain letter "m" closing a sequence of numeric codes that may change the way the terminal will display some text.
So, for front-face red text, you may want to do:
print("\x1b[31mThis text in red\x1b[39m normal color").
(note that the numbers are also plain decimal strings with the digits)
You will note that the code "74" is reserved for "subscript" code - however, I don't know of a terminal emulator which implements it.

Related

Why a string starting with 'cat....' outputs with a different color in Programiz?

I can't figure out why when I print a string starting with 'cat..' (like category, cathedral, catch, ...) in the Programiz Online Python Compiler it appears in green (or gray and italic in dark mode) instead of black (or white in dark mode).
print('cathedral')
print('car')
Anyone knows? Is there a joke or something I'm missing?
Tried in a different Programiz Online Compiler, like the C one, and it also happens there!
Ok, since this is client side, the easy way to know is to inspect javascript code (even if it is minified, that part is quite readable. Just search for cat in it)
And, indeed, there is explicit code to tread as "batch comment" some regexp in the output area.
Including ^cat.*. And many others.
For example
print("/tmp/bla")
print(">") # but with nothing else
print("node bla.js")
print("mono ouchNoPlease.cs")
print("javac monoWasNotThatBadAfterAll.java")
Why cat is among a series of regexp apparently for compiler commands, I don't know. And why gcc or many other classical compilers aren't, neither. Nor why, since cat is, no other unix/bash/batch command are.
But whatever the reason, it is no accident, and there are explicit code to color anything starting with cat
Edit: my (other) mistake, gcc is in the list. It was just before cat, and since I read this code by researching cat...
Here is the extract of the javascript code of programmiz:
[{token:["comment.line.colons.dosbatch"],regex:"(?:^|\\b)gcc($|\\s.*$)",caseInsensitive:!0},
{token:["comment.line.colons.dosbatch"],regex:"^(/tmp).*$",caseInsensitive:!0},
{token:["comment.line.colons.dosbatch"],regex:/^g\+\+.*$/,caseInsensitive:!0},
{token:["comment.line.colons.dosbatch"],regex:/^cat.*$/,caseInsensitive:!0},
{token:["comment.line.colons.dosbatch"],regex:/^>/},
{token:["comment.line.colons.dosbatch"],regex:"^(javac).*$",caseInsensitive:!0},
{token:["comment.line.colons.dosbatch"],regex:"^(csc|mono).*$",caseInsensitive:!0},
{token:["comment.line.colons.dosbatch"],regex:"^(node).*$",caseInsensitive:!0}]
Wider context is that this is inserted into Ace (since programmiz use Ace editor) syntax coloring rules.
So, the only outliers in the list are > and /tmp/ for the non command strings. And for commands, well, it is precisely cat.
Maybe there is a language compiler/interpreter outside unix world that is called cat I am not aware of. Or maybe cat is considered to be a very raw interpreter (after all, it does execute a very simple language that prints all instructions :D)
After testing out various strings, I think the terminal emulator is lazy and is treating the word "cat" as the bash command cat. The color will only change if the first 3 letters are exactly "cat"; if anything separates them, or there is a space before them, nothing happens. Similarly, it does not at all care what comes after it. It is also interesting that by first three letters, it is looking at the terminal output and not the python string. for instance print("\ncat") still produces the different color, just on a different line.
I attempted to test calling cat through python to see if I was right, but the compiler refuses to load os or subprocess. I can confirm it happens on my end though.

Translate Vim keycode string ("<C-Z>") into actual keycode number (^Z = 26) in Python

I'm trying to port my Vim 8.0 configuration (~/.vimrc) to Python. That is, I'm setting Vim options as fields on vim.options mapping:
import vim
# set wildmenu
vim.options['wildmenu'] = True
# set wildcharm=<C-Z>
vim.options['wildcharm'] = ord('^Z') # [Literal ^Z (ASCII 26), CTRL-V CTRL-Z]
# set wildchar=<F10>
vim.options['wildchar'] = -15211 # extracted from Vim
The wildchar and wildcharm Vim options are of type "number". As far as I understand, they expect a kind of a keycode (at least in simple cases it is the ASCII code of the character in question).
In Vimscript, when you say something like set wildchar=<F10>, Vim translates the Vim-specific textual representation into a numeric keycode.
In Python, this is not the case (vim.options['wildchar'] = '<F10>' gives a TypeError).
For simple cases, it is possible to use ord() on a string containing the literally typed control character (see above with Ctrl-Z). However, a key like F10 produces multiple characters, so I can't use ord() on it.
In the end, I want to be able to do something like this:
vim.options['wildchar'] = magic('<F10>')
Does this magic() function exist?
Edit: I'm not asking how to invoke Vimscript code from Python (i. e. vim.command(...)). I understand that the encompassing problem can be trivially solved this way, but I'm asking a different question here.
:python vim.command("set wildchar=<F10>")
See the vim.command documentation for more explanation.

How do I color parts of a string BEFORE drawing the string to the screen with curses?

Is there any way that I can color a word in a string before I even addstr it to the curses screen? I have tried to do this at a low-level by concatenating things like "\033[31m" (and then "\033[0m" at the end) to the string, but curses does not recognize that and just spits out something like: this is a ^[[31mlink^[[0m. If you do not understand so far, this may help:
# pseudocode
a = "this is a link"
replace "link" in a with colorRed("link")
Thank you.
No: programs that use curses do not send escape sequences. Instead, they pass strings and attributes. The curses library puts those together and sends escape sequences.
In the C interface for curses, that could be done per-character by OR'ing the attribute onto chtype values (or packing cchar_t using setcchar). Alternatively, one could set an attribute on the window and write a string using that attribute with addstr.
Python provides (according to its documentation) a different interface to addstr. The section Attributes and Color shows this example:
stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_REVERSE)
to add a reverse-video string, and this:
stdscr.addstr("Pretty text", curses.color_pair(1))
to add a string using color pair #1. Color pairs combine foreground (text) and background colors.
Python's interface to changing the window attributes more closely resembles the C interface: it provides attrset, attron, bkgd methods as shown in its documentation for Window Objects.
As a general guideline, you would not get good results by writing your own escape sequences directly (bypassing the curses library):
curses uses its own output buffering, which may not be connected to your standard output buffer (so things may be written in an unexpected order)
if you wrote something that changed the screen's appearance, curses would not know about that, and the result would not be helpful.

AutoKey - clipboard.get_selection() function fails on certain strings

I've simplified my script so you can focus on the essence my problem.
In AutoKey (not AutoHotKey), I made a Hot-Key (shift-alt-T) that performs this script on any string I have highlighted (like in gedit for example -- but any other gui editor too).
strSelectedText = clipboard.get_selection()
keyboard.send_keys(" " + strSelectedText)
The script modifies the highlighted text and adds a space to the beginning of the string.
It works for most strings I highlight, but not this one:
* Copyright © 2008–2012 Lonnie Best. Licensed under the MIT License.
It works for this string:
* Add a Space 2.0.1
but not on this one:
* Add a Space 2.0.1 –
At the python command prompt, it has no problem any of those strings, yet the clipboard.get_selection() function seems to get corrupted by them.
I'm rather new to python scripting, so I'm not sure if this is an AutoKey bug, or if I'm missing some knowledge I should know about encoding/preparing strings in python.
Please help. I'm doing this on Ubuntu 12.04:
sudo apt-get install autokey-qt
There is no keyboard key for the copyright symbol, or any non-ASCII character like the EN DASH in your third example. Your script code would have to somehow translate any non-ASCII Unicode characters into the appropriate keyboard sequences to generate them. Perhaps you could grab from the clipboard and use a clipboard function to paste the modified string back into your App.
This is a bug in the Python 3 implementation of autokey (special characters not passed through keyboard.send_keys). See GitHub for example.

^H ^? in python

Some terminals will send ^? as backspace, some other terminals will send ^H.
Most of the terminals can be configured to change their behavior.
I do not want to deal with all the possible combinations but I would like to accept both ^? and ^H as a backspace from python.
doing this
os.system("stty erase '^?'")
I will accept the first option and with
os.system("stty erase '^H'")
I will accept the second one but the first will be no longer available.
I would like to use
raw_input("userinput>>")
to grab the input.
The only way I was able to figure out is implementing my own shell which works not on "raw based input" but on "char based input".
Any better (and quicker) idea?
The built-in function raw_input() (or input() in Python 3) will automatically use the readline library after importing it. This gives you a nice and full-feautured line editor, and it is probably your best bet on platforms where it is available, as long as you don't mind Readline having a contagious licence (GPL).
I don't know your question exactly. IMO, you need a method to read some line-based text(including some special character) from console to program.
No matter what method you use, if read this character have special mean in different console, you should confront a console(not only system-specific, but also console-specific) question, all text in console will be store in buffer first, and then show in screen, finally processed and send in to your program. Another way to surround this problem is to use a raw line-obtaining console environment.
You can add a special method(a decorator) to decorate the raw_input() or somewhat input method to process special word.
After solved that question
using this snippet can deal with input,:
def pre():
textline=raw_input()
# ^? should replace to the specific value.
textline.replace("^?","^H")
return textline
To be faster, maybe invoke some system function depend on OS is an idea. But in fact, IO in python is faster enough for common jobs.
To fix ^? on erase do stty erase ^H

Categories

Resources