Citizen SP
Citizen SP

Reputation: 1411

Open documents in the browser

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())

Upvotes: 0

Views: 636

Answers (2)

Julia K
Julia K

Reputation: 46

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')

Upvotes: 1

Waylan
Waylan

Reputation: 42487

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.

Upvotes: 0

Related Questions