I am using the following code (within Cherrypy) to open a file on the network share. (http://localhost:8080/g?filename=filename.docx)
This seems to work fine, but when I open a file, for example a Word document, Word is opening behind the current browser window.
How to open a link and focus on the window?
import os
import cherrypy
import webbrowser
class StringGenerator(object):
#cherrypy.expose
def index(self):
return "Hello world!"
#cherrypy.expose
def g(self, filename):
webbrowser.open(r'\\computer\share\filename.docx', new=2, autoraise=True)
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())
You can use pywin32 libraries. For example:
import win32com.client
import win32gui
import win32process
hwnd = win32gui.GetForegroundWindow()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate('filename.docx')
The documentation states (in part):
Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
The last part of that comment is the problem. In fact, in reviewing the source code, it appears that on some systems a system specific command is called which opens the default program by file type. As the default program for a Word document is MS Word, the file will be opened in that program. As the default program for a web page is a browser, a web page will be opened in the default browser.
However, you can tell webbroswer to use a specific program. See this answer for how to do that.
Related
I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using raw_input which is most unfriendly, especially because the user can't copy/paste the path. I would like a quick and easy way to present a file selection dialog to the user, they can select the file, and then it's loaded to the database. (In my use case, if they happened to chose the wrong file, it would fail parsing, and wouldn't be a problem even if it was loaded to the database.)
import tkFileDialog
file_path_string = tkFileDialog.askopenfilename()
This code is close to what I want, but it leaves an annoying empty frame open (which isn't able to be closed, probably because I haven't registered a close event handler).
I don't have to use tkInter, but since it's in the Python standard library it's a good candidate for quickest and easiest solution.
Whats a quick and easy way to prompt for a file or filename in a script without any other UI?
Tkinter is the easiest way if you don't want to have any other dependencies.
To show only the dialog without any other GUI elements, you have to hide the root window using the withdraw method:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
Python 2 variant:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
You can use easygui:
import easygui
path = easygui.fileopenbox()
To install easygui, you can use pip:
pip3 install easygui
It is a single pure Python module (easygui.py) that uses tkinter.
Try with wxPython:
import wx
def get_path(wildcard):
app = wx.App(None)
style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)
if dialog.ShowModal() == wx.ID_OK:
path = dialog.GetPath()
else:
path = None
dialog.Destroy()
return path
print get_path('*.txt')
pywin32 provides access to the GetOpenFileName win32 function. From the example
import win32gui, win32con, os
filter='Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0'
customfilter='Other file types\0*.*\0'
fname, customfilter, flags=win32gui.GetOpenFileNameW(
InitialDir=os.environ['temp'],
Flags=win32con.OFN_ALLOWMULTISELECT|win32con.OFN_EXPLORER,
File='somefilename', DefExt='py',
Title='GetOpenFileNameW',
Filter=filter,
CustomFilter=customfilter,
FilterIndex=0)
print 'open file names:', repr(fname)
print 'filter used:', repr(customfilter)
print 'Flags:', flags
for k,v in win32con.__dict__.items():
if k.startswith('OFN_') and flags & v:
print '\t'+k
Using tkinter (python 2) or Tkinter (python 3) it's indeed possible to display file open dialog (See other answers here). Please notice however that user interface of that dialog is outdated and does not corresponds to newer file open dialogs available in Windows 10.
Moreover - if you're looking on way to embedd python support into your own application - you will find out soon that tkinter library is not open source code and even more - it is commercial library.
(For example search for "activetcl pricing" will lead you to this web page: https://reviews.financesonline.com/p/activetcl/)
So tkinter library will cost money for any application wanting to embedd python.
I by myself managed to find pythonnet library:
Overview here: http://pythonnet.github.io/
Source code here: https://github.com/pythonnet/pythonnet
(MIT License)
Using following command it's possible to install pythonnet:
pip3 install pythonnet
And here you can find out working example for using open file dialog:
https://stackoverflow.com/a/50446803/2338477
Let me copy an example also here:
import sys
import ctypes
co_initialize = ctypes.windll.ole32.CoInitialize
# Force STA mode
co_initialize(None)
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import OpenFileDialog
file_dialog = OpenFileDialog()
ret = file_dialog.ShowDialog()
if ret != 1:
print("Cancelled")
sys.exit()
print(file_dialog.FileName)
If you also miss more complex user interface - see Demo folder
in pythonnet git.
I'm not sure about portability to other OS's, haven't tried, but .net 5 is planned to be ported to multiple OS's (Search ".net 5 platforms", https://devblogs.microsoft.com/dotnet/introducing-net-5/ ) - so this technology is also future proof.
If you don't need the UI or expect the program to run in a CLI, you could parse the filepath as an argument. This would allow you to use the autocomplete feature of your CLI to quickly find the file you need.
This would probably only be handy if the script is non-interactive besides the filepath input.
Another os-agnostic option, use pywebview:
import webview
def webview_file_dialog():
file = None
def open_file_dialog(w):
nonlocal file
try:
file = w.create_file_dialog(webview.OPEN_DIALOG)[0]
except TypeError:
pass # user exited file dialog without picking
finally:
w.destroy()
window = webview.create_window("", hidden=True)
webview.start(open_file_dialog, window)
# file will either be a string or None
return file
print(webview_file_dialog())
Environment: python3.8.6 on Mac - though I've used pywebview on windows 10 before.
I just stumbled on this little trick for Windows only: run powershell.exe from subprocess.
import subprocess
sys_const = ssfDESKTOP # Starts at the top level
# sys_const = 0x2a # Correct value for "Program Files (0x86)" folder
powershell_browse = "(new-object -COM 'Shell.Application')."
powershell_browse += "BrowseForFolder(0,'window title here',0,sys_const).self.path"
ret = subprocess.run(["powershell.exe",powershell_browse], stdout=subprocess.PIPE)
print(ret.stdout.decode())
Note the optional use of system folder constants. (There's an obscure typo in shldisp.h that the "Program Files (0x86)" constant was assigned wrong. I added a comment with the correct value. Took me a bit to figure that one out.)
More info below:
System folder constants
I want to open a website in my local computer's web browser (Chrome or Internet Explorer) using Python.
open("http://google.co.kr") # something like this
Is there a module that can do this for me?
The webbrowser module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM
import webbrowser
webbrowser.open('http://google.co.kr', new=2)
From the doc.
The webbrowser module provides a high-level interface to allow
displaying Web-based documents to users. Under most circumstances,
simply calling the open() function from this module will do the right
thing.
You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible.
If new is 1, a new browser window is opened if possible. If new is 2,
a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)
import webbrowser as wb
wb.open_new_tab('http://www.google.com')
The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?
The proper way to do this is:
import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')
To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.
However, doing this didn't work right off the bat for me. Every time, I would get the error:
Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:
C:\Program Files (x86)\Google\Chrome\Application
You should check whether it is here or not for yourself.
To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.
Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.
Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:
C:\Program Files (x86)\Google\Chrome\Application
Click save and exit out of there. Then make sure you reboot your computer.
Hope this helps!
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
I think it should be
import webbrowser
webbrowser.open('http://gatedin.com')
NOTE: make sure that you give http or https
if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE.
here you are importing webbrowser library
I had this problem.When I define firefox path my problem had been solved.
import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd) like subprocess, os, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
Example
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click which mainly used for writing command line utilities.
here is how
import click
click.launch('http://your_url')
Its a 2 liner! :D
You are a great programmer so never give up!
#Use web-browser.
import webbrowser as w
w.open("https://google.com")
#remember to include https://
#If you want to make a page open if you click a button do this :
from tkinter import *
#^ Imports tk
import webbrowser as w
#^ Imports wb
x = Tk()
#Makes main window
def clicked() :
w.open("https://google.com")
#Defined the click function. (We'll use this later.)
link = Button(x, text="Click Me!", command=clicked)
link.pack(pady=20, padx=20)
#Our button
x.mainloop()
#Tkinter mainloop
If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:
from threading import Timer
from time import sleep
import subprocess
import platform
# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running
platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}
browser = None
def open_browser():
global browser
platform_name = platform.system()
if platform_name in platform_browser:
browser = subprocess.Popen(platform_browser[platform_name])
else:
print(":-(")
Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch
sleep(20) # start e.g. your python web server here instead
browser.kill()
If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website.
e.g.
import webbrowser
webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)
I'm currently trying to open my chrome default new tab page using the webbrowser module in python. I've gotten it to work for opening up random urls, however, when I try chrome://newtab as the url, I just get a message saying that there are "no apps installed to open this type of link".
Here's the relevant bit of code (not much):
import webbrowser
webbrowser.open_new_tab("chrome://newtab")
Yes, chrome is my default browser. Thanks for the help!
Notice that the documentation states that:
Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
It has been a while since I looked at this, but my recollection is that on at least some systems, the way it works under the hood is that is passes the given URI to a system specific built-in command which then opens the URI in the system default for whatever type of URI was passed in. In other words, the default application for a given file type is used. It doesn't matter if the URI points to a local file or not. Therefore, the URI http://examplce.comn/somefile.pdf would open the PDF file on the system default PDF viewer, which may not be the browser. As the documentation notes, this works by accident due to the underlying implementation.
However, in a different OS, such a system specific command doesn't exist, and all URIs will be opened in a web browser.
You failed to mention which OS you are working on (and I forget which OS works which way), but I suspect you are working on an OS of the first type. You might (again depends on which system you have) be able override the default behavior by specifying that a specific browser be used.
You could try setting the environment variable BROWSER as an os.pathsep-separated list of browsers to try in order. Check the value of os.pathsep (import os; print os.pathsep) to see which character is used by your system (usually ':' for POSIX or ';' for Windows) and then use that character to separate items in the list. Of course, you may need to only assign one item to the list (chrome), in which case you don't need to use the separator at all. Like this (be sure to use the correct path for your system):
SET BROWSER="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Or, you could try using webrowser.get() to choose your browser programically. However, support for Chrome hasn't been added until Python 3.3. If you are using Python 3.3+, then try:
import webbrowser
chrome = webbrowser.get('google-chrome') # or webbrowser.get('chrome')
chrome.open_new_tab('chrome://newtab')
Note: the above is untested. I don't know which system you have and am therefore not able to replicate your specific setup. YMMV.
Update:
As I now know you are on a pre-Python 3.3 windows machine perhaps the following will help. You can also register a browser so that Python knows about it:
pth = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(pth))
chrome = webbrowser.get('chrome')
chrome.open_new_tab('chrome://newtab')
Seemingly Bulletproof Rock Solid Command Line From Python Option
In development, the methods above worked well for me. Then I moved my code to a production server. I found different flavors of Windows don't all play the same with python's webdriver module - I was very bummed!
I needed a bulletproof method to open auto generated html reports in a specific order.
The code below is a modification of what I did that worked very well.
import subprocess as SP
import time
def display_reports_in_chrome(param_1, param_2):
front = f'start chrome.exe {param_1}\\reports\\' # beginning of command string
reports_list = [
'report_1.html', 'report_2.html', 'report_3.html', 'report_4.html']
url_list = []
for report in reports_list:
url_list.append(f'{front}{param_2}\\{report}') # complete build of commands
for url_cs in url_list: # url_cs = url open command string
time.sleep(0.1) # helps to ensure the tabs order correctly
clo = SP.run(url_cs, shell=True, capture_output=True) # actual shell command
# Stuff below makes sure it worked
check = clo.returncode == 0
error = clo.stderr.decode('utf-8')
url_open_ok = check and not error
err_msg = f'{error}. Let Thom know please!'
assert url_open_ok, err_msg
I should point out that I was enlightened to try this by this answer on SuperUser
How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.
First, you need to download and install pywin32. Import these modules in your script:
import win32gui
import win32con
If Google Chrome is the currently active window, first get the window handle by:
hwnd = win32gui.GetForegroundWindow()
(Otherwise, find the Google Chrome window handle by using win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)
It seems the only way to get the URL is to get the text in the "omnibox" (address bar). This is usually the tab's URL, but could also be any partial URL or search string that the user is currently typing.
Also, the URL in the omnibox won't include the "http://" prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include "https://" or "ftp://" if those protocols are used.
So, we find the omnibox child window inside the current Chrome window:
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
This will of course break if the Google Chrome team decides to rename their window classes.
And then we get the "window text" of the omnibox, which doesn't seem to work with win32gui.GetWindowText for me. Good thing there's an alternative that does work:
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).
There you go!
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.
The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage
Run this and switch to Chrome window you want to grab address from:
from time import sleep
import uiautomation as automation
if __name__ == '__main__':
sleep(3)
control = automation.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
if len(controlList) == 1:
control = controlList[0]
else:
control = controlList[1]
address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
print address_control.CurrentValue()
I quite new to StackOverFlow so apologies if the comment is out of tone.
After looking at :
Selenium,
launching chrome://History directly,
doing some keyboard emulation : copy/paste with Pywinauto,
trying to use SOCK_RAW connections to capture the headers as per the Network tab of the DevTool (this one was very interesting),
trying to get text of the omnibus/searchBar window element,
closing and reopening chrome to read the history tables,
....
I resulted in copy/pasting the History file itself (\AppData\Local\Google\Chrome\User Data\Default\History) into my application folder when the title of the window (retrieved using the hwnd + win32) is missing from "my" urls table.
This can be done even if the sqlite db is locked and does not interfere with the user experience.
Very basic solution that requires : sqlite3, psutil, win32gui.
Hope that helps.
How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.
First, you need to download and install pywin32. Import these modules in your script:
import win32gui
import win32con
If Google Chrome is the currently active window, first get the window handle by:
hwnd = win32gui.GetForegroundWindow()
(Otherwise, find the Google Chrome window handle by using win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)
It seems the only way to get the URL is to get the text in the "omnibox" (address bar). This is usually the tab's URL, but could also be any partial URL or search string that the user is currently typing.
Also, the URL in the omnibox won't include the "http://" prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include "https://" or "ftp://" if those protocols are used.
So, we find the omnibox child window inside the current Chrome window:
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
This will of course break if the Google Chrome team decides to rename their window classes.
And then we get the "window text" of the omnibox, which doesn't seem to work with win32gui.GetWindowText for me. Good thing there's an alternative that does work:
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).
There you go!
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.
The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage
Run this and switch to Chrome window you want to grab address from:
from time import sleep
import uiautomation as automation
if __name__ == '__main__':
sleep(3)
control = automation.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
if len(controlList) == 1:
control = controlList[0]
else:
control = controlList[1]
address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
print address_control.CurrentValue()
I quite new to StackOverFlow so apologies if the comment is out of tone.
After looking at :
Selenium,
launching chrome://History directly,
doing some keyboard emulation : copy/paste with Pywinauto,
trying to use SOCK_RAW connections to capture the headers as per the Network tab of the DevTool (this one was very interesting),
trying to get text of the omnibus/searchBar window element,
closing and reopening chrome to read the history tables,
....
I resulted in copy/pasting the History file itself (\AppData\Local\Google\Chrome\User Data\Default\History) into my application folder when the title of the window (retrieved using the hwnd + win32) is missing from "my" urls table.
This can be done even if the sqlite db is locked and does not interfere with the user experience.
Very basic solution that requires : sqlite3, psutil, win32gui.
Hope that helps.