Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open URL and return to shell

I'm running a script on python 3 that opens a URL using webbrowser.open() and immediately requires an input from the user. The problem is that the active window is now that of the browser instead of the python shell and an Alt-Tab or click is always required to provide the answer. You can imagine how frustrating it can be for thousands of images. The code is as simple as this:

 for rP in images:
     webbrowser.open(rP)
     decision = str(input('Is image '+str(rP)+' ok?')

I guess there are three ways of solving this but I can't seem to find an implementation for any of them. I've tried the 'autoraise' option in the webbrowser.open() command to no avail. I'm guessing that either solution will be so simple that I'll be banging my head afterwards.

So:
Solution #1: Have a command before the input line that makes the shell window active instead of the browser.
Solution #2: Open the webpage in the background thus never leaving the shell.
Solution #3: Give the shell window an "always on top" property.

Any ideas?

like image 870
dinos66 Avatar asked Nov 10 '22 01:11

dinos66


1 Answers

Windows

This was tested with Python 2.7.8, with a double AppActivate trick posted by partybuddha, and a sleep trick posted by eryksun:

from webbrowser import open as browse
from win32com.client import Dispatch
from win32gui import GetForegroundWindow
from win32process import GetWindowThreadProcessId
from time import sleep

images=['http://serverfault.com', 'http://stackoverflow.com']

for rP in images:
    _, pid = GetWindowThreadProcessId(GetForegroundWindow())
    browse(rP)
    sleep(1)
    shell = Dispatch("WScript.Shell")
    shell.AppActivate(pid)
    shell.AppActivate(pid)
    decision = raw_input('Is image ' + str(rP) + ' ok? ')

Without the 1 second sleep, the browser kept the focus, as if the AppActivate was happening too soon.

OS X

#!/usr/bin/env python
from webbrowser import open as browse
from subprocess import check_output

images=['http://serverfault.com', 'http://stackoverflow.com']

for rP in images:
     term = check_output(['/usr/bin/osascript', '-e',
         'copy path to frontmost application as text to stdout']).strip()
     browse(rP)
     check_output(['/usr/bin/osascript', '-e',
         'tell application "%s" to activate' % term])
     decision = raw_input('Is image ' + str(rP) + ' ok? ')

This code was tested with Python 2.7.5, so it may need tweaking to work with Python 3, but the core idea is to use osascript to get the frontmost application, and then activate it after opening the URL in the browser window.

like image 130
Nick Russo Avatar answered Nov 14 '22 23:11

Nick Russo