Making clickable text in Python [duplicate] - python

I'm working on a console application. My application uses urwid lib. In some cases, I need to show very long hyperlinks as short text inside table columns. I want to open links in the browser when I click on the text inside the column.
So, my question is:
It is possible to print text as a hyperlink to the console?
Can you provide a small example of how to print text as a hyperlink using python?

A bit late, but there totally is a way to do that now, without curses or anything, just pure text and collaboration from your terminal emulator.
def link(uri, label=None):
if label is None:
label = uri
parameters = ''
# OSC 8 ; params ; URI ST <name> OSC 8 ;; ST
escape_mask = '\033]8;{};{}\033\\{}\033]8;;\033\\'
return escape_mask.format(parameters, uri, label)
Call that function with link('https://example.com/') to get a simple, clickable link, or link('https://example.com/', 'example') for a custom label.
Note that links are faintly underlined in your terminal, and not all of them support the feature.

Yes, using some tools, like gNewt or Curses, you could create a button and 'on click' do an action (like open a browser to a given url).
gNewt : http://gnewt.sourceforge.net/
nCurses : https://docs.python.org/3.7/library/curses.html
Otherwise, it's the terminal application that will manage the text you give it, and if it doesn't implement uri's recognition your program won't work as you'd like.

No, some consoles do recognize urls and convert them to a clickable hyperlink. All you can do is make it easy to recognize for console applications by putting a http:// in your url.
Also see
How does bash recognize a link?

Related

webbrowser python open new url in same tab. Does this ever work?

It seems to me that Python's webbrowser 'new=0' functionality (see here), which opens a new url in the same tab or window, is not ever working.
The documentation uses dodgy language like "if possible" to mask this problem.
Has anyone seen any success with this functionality in the webbrowser module? Are there any known workarounds to achieve this functionality?
I have tried setting the webbrowser with
webbrowser.get(TYPE)
before continuing with opening urls. I have also tried using a slew of different browsers, however still have seen no success. Is this just not possible anymore? Should I just use selenium?
Among others, I have checked out this post from 7 years ago. I am hoping things have changed since then and people have found a way around this.
Any help or insight is much appreciated.
I'm using MacOS and Chrome and ran into this. I noticed that for MacOS, webbrowser.py just builds a little applescript and opens the URL with the 'open location' command, e.g.,
script = 'open location "%s"' % url.replace('"', '%22')
The built-in 'open location' command doesn't appear to support opening a url in an existing tab
I searched around in applescript examples and found that you can use commands from the Chrome applescript dictionary to open URL in the active tab like so:
tell application "Google Chrome"
tell front window
set URL of active tab to "www.google.com"
end tell
end tell
I only needed to do this on a local project, so I just went with the dirty fix of overwriting the string in the 'script' variable to force it to use the latter format, like so:
# script = 'open location "%s"' % url.replace('"', '%22')
script = '''tell application "Google Chrome"
tell front window
set URL of active tab to "%s"
end tell
end tell ''' % url.replace('"', '%22')

Print my wx.Panel after formatting it

I am working on an app using wxPython and it kind of needs to print the info shown to the user. On click of the print button, The data shown in the current panel has to be formatted a bit and then be sent to the printer queue.
Google searches give me ways to print text documents. How do I go about with this?
wxPython provides a couple of printing options. You can check out the full printing framework it provides here:
http://wxpython.org/Phoenix/docs/html/printing_framework_overview.html
http://wxpython.org/Phoenix/docs/html/Printout.html
It's fairly complex, but it is also the most flexible way to print using wxPython. They do have another option though that's called HtmlEasyPrinting:
http://wxpython.org/Phoenix/docs/html/html.HtmlEasyPrinting.html
You might want to take a look at that if you're new to wxPython. Of course, you could also use the reportlab package to generate a nicely formatted PDF of your text and then send that to the printer or just open it in the user's default PDF viewer so they can print it.

Using Mac’s Dictation Inside Python

Does anyone have any ideas on how to use the Mac’s built-in dictation tool to create strings to be used by Python?
To launch a dictation, you have to double-press the Fn key inside any text editor. If this is the case, is there a way to combine the keystroke command with the input command? Something like:
Step 1: Simulate a keystroke to double-press the Fn key, launching the Dictation tool, and then
Step 2. Creating a variable by using the speech-to-text content as part of the input function, i.e. text_string = input(“Start dictation: “)
In this thread (Can I use OS X 10.8's speech recognition/dictation without a GUI?) a user suggests he figured it out with CGEventCreateKeyboardEvent(src, 0x3F, true), but there is no code.
Any ideas? Code samples would be appreciated.
UPDATE: Thanks to the suggestions below, I've imported AppScript. I'm trying the code to work along these lines, with no success:
from appscript import app, its
se = app('System Events')
proc = app.processes[its.frontmost == True]
mi = proc.menu_bars[1].menu_bar_items['Edit'].menus[1].menu_items['Start Dictation']
user_voice_text = input(mi.click())
print(user_voice_text)
Any ideas on how I can turn on the dictation tool to be input for a string?
UPDATE 2:
Here is a simple example of the program I'm trying to create:
Ideally i want to launch the program, and then have it ask me: "what is 1 + 1?"
Then I want the program to turn on the dictation tool, and I want the program to record my voice, with me answering "two".
The dictation-to-text function will then pass the string value = "two" to my program, and an if statement is then used to say back "correct" or "incorrect".
Im trying to pass commands to the program without ever typing on the keyboard.
First, FnFn dictation is a feature of the NSText (or maybe NSTextView?) Cocoa control. If you've got one of those, the dictated text gets inserted into that control. (It also uses that control's existing text for context.) From the point of view of the app using an NSTextView, if you just create a standard Edit menu, the Start Dictation item gets added to the end, with FnFn as a shortcut, and anything that gets dictated appears as input, just like input typed on a keyboard, or pasted or dragged with the mouse, or via any other input method.
So, if you don't have a GUI app, enabling dictation is going to be pointless, because you have no way to get the input.
If you do have a GUI app, the simplest thing to do is just get the menu item via NSMenu, and click the item.
You're almost certainly using some kind of GUI library, like PyQt or Tkinter, which has its own way of accessing your app's menu. But if not, you can do it directly through Cocoa (using PyObjC—which comes with Apple's pre-installed Python, but which you'll have to pip install if you're using a third-party Python):
import AppKit
mb = AppKit.NSApp.mainMenu()
edit = mb.itemWithTitle_('Edit').submenu()
sd = edit.indexOfItemWithTitle_('Start Dictation')
edit.performActionForItemAtIndex_(sd)
But if you're writing a console program that runs in the terminal (whether Terminal.app or an alternative like iTerm), the app you're running under has its own text widget and Edit menu, and you can parasitically use its menu instead.
The problem is that you don't have permission to just control other apps unless the user allows it. In older versions of OS X, this was done just by turning on "assistive scripting for accessibility" globally. As of 10.10, there's an Accessibility anchor in the Privacy tab of the Security & Privacy pane of System Preferences that has a list of apps that have permissions. Fortunately, if you're not on the list, the first time you try to use accessibility features, it'll pop up a dialog, and if the user clicks on it, it'll launch System Preferences, reveal that anchor, add your app to the list with the checkbox disabled, and scroll it into view, so all the user has to do is click the checkbox.
The AppleScript to do this is:
tell application "System Events"
click (menu item "Start Dictation" of menu of menu bar item "Edit"
of menu bar of (first process whose frontmost is true))
end tell
The "right" way to do the equivalent in Python is via ScriptingBridge, which you can access via PyObjC… but it's a lot easier to use the third-party library appscript:
from appscript import app, its
se = app('System Events')
proc = app.processes[its.frontmost == True]
mi = proc.menu_bars[1].menu_bar_items['Edit'].menus[1].menu_items['Start Dictation']
mi.click()
If you really want to send the Fn key twice, the APIs for generating and sending keyboard events are part of Quartz Events Services, which (even though it's a CoreFoundation C API, not a Cocoa ObjC API) is also wrapped by PyObjC. The documentation can be a bit tricky to understand, but basically, the idea is that you create an event of the appropriate type, then either post it to a specific application, an event tap, or a tap location. So, you can create and send a system-wide key-down Fn-key event like this:
evt = Quartz.CGEventCreateKeyboardEvent(None, 63, True)
Quartz.CGEventPost(Quartz.kCGSessionEventTap, evt)
To send a key-up event, just change that True to False.

Copy and paste text in python

I'm currently developing a language transition software for linux using python GTK. it has two entries. what it basically does is, when the user type some word in a text entry 1, the translated text appears in text entry 2 and when the user press space bar, I want to paste the translated text to another application's text area. not to a text entry in my application. I think it needs to switch to the other application, paste the text and switch back to my application.
As an example, if gedit is opened in background, when a user type a word in my application and press the space bar, the translated word should be pasted in gedit.
Sometimes it may be possible to complete my task by set my application window as a popup window(type=WINDOW_POPUP) without set it as top level window(type=WINDOW_TOPLEVEL). but I'm not clear with that.
I think the problem is clear to you. If anyone can help me to solve this problem, it would be a great help for me. Thanks all.
this looks like a dbus solution and not a fun one. As for clipboard manipulation in GTK http://developer.gnome.org/gtk3/stable/gtk3-Clipboards.html will get you where you need to go, most of the C functions have a direct equivalent in python ( http://developer.gnome.org/pygtk/stable/class-gtkclipboard.html ).
Communication between applications in GTK+ is not a whole lot of fun and when I worked on a project that had to do so, I ended up using DBUS (C++) but there might be a good python port for dbus, I haven't checked.

How do I get the selected text in desktop application using python-dbus?

For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?
Some simple but working piece of script is appreciated greatly.
Thanks!
You don't need D-Bus, simply listen to changes for the middle-click (Selection) clipboard with for example Gtk:
import gtk
def _clipboard_changed(clipboard, event):
text = clipboard.wait_for_text()
clip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)
clip.connect("owner-change", _clipboard_changed)
Gnome Do has a few plug-ins that use the selected text. I'm not sure how it is implemented (and if it uses DBus), but the code should reveal all. :)

Categories