Open URL and return to shell

I am running a python 3 script that opens a URL using webbrowser.open () and immediately requires user input. The problem is that the active window is now the browser window instead of the python shell, and Alt-Tab or click is always required to respond to this request. You can imagine how this can upset thousands of images. The code is as simple as this one:

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

I assume there are three ways to solve this, but I cannot find an implementation for any of them. I tried the "autoraise" option on the webbrowser.open () command to no avail. I assume that any solution will be so simple that I will hit my head after that.

So:
Solution # 1: before the input command, enter a command that makes the shell window active, not the browser.
Solution # 2: Open the web page in the background so that you donโ€™t leave the shell.
Solution # 3: Give the shell an โ€œalways on topโ€ window.

Any ideas?

+5
source share
2 answers

Window

This was tested using Python 2.7.8, with the AppActivate double trick posted by partybuddha and the 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 a 1 second sleep, the browser left focus, as if 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 has been tested with Python 2.7.5, so it may take some time to work with Python 3, but the main idea is to use osascript to get the very first application, and then activate it after opening the URL in a browser window.

+1
source

If you use Selenium , focus automatically returns to the browser after .get() .

0
source

Source: https://habr.com/ru/post/1202872/


All Articles