Python webbrowser.open() Examples

The following are 30 code examples of webbrowser.open(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module webbrowser , or try the search function .
Example #1
Source File: web.py    From svviz with MIT License 6 votes vote down vote up
def run(port=None):
    import webbrowser, threading

    if port is None:
        port = getRandomPort()

    # load()
    url = "http://127.0.0.1:{}/".format(port)
    logging.info("Starting browser at {}".format(url))
    # webbrowser.open_new(url)

    threading.Timer(1.25, lambda: webbrowser.open(url) ).start()

    app.run(
        port=port#,
        # debug=True
    ) 
Example #2
Source File: runTests.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def run_mpi_coverage_tests(coverage_cmd, nproc=4):
    shutil.copy('mpi/setup.cfg.mpi', 'setup.cfg')

    #OLD: worked with python2.7, but not with 3 (where .coverage files turned to JSON)
    #mpicommands = ('time mpiexec -np %s python%s mpi/runtests.py -v ' % (str(nproc), '' if version is None else version)+
    #               '--with-coverage --cover-package=pygsti --cover-erase mpi/testmpi*.py  ' +
    #               '> ../output/coverage_tests_mpi.out 2>&1')

    mpicommands = ('time mpiexec -np %s %s run -p ' % (str(nproc), coverage_cmd) +
                   '--source=pygsti mpi/runtests.py -v mpi/testmpi*.py ' +
                   '> ../output/coverage_tests_mpi.out 2>&1')

    with open('../output/mpi_output.txt', 'w') as output:
        returned = subprocess.call(mpicommands, shell=True, stdout=output, stderr=output)
    with open('../output/mpi_output.txt', 'r') as output:
        print(output.read())
    os.remove('setup.cfg')
    return returned 
Example #3
Source File: notebook.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def launch(self, outputFilename, templateFilename=DefaultTemplate, port='auto'):
        '''
        Save and then launch this notebook

        Parameters
        ----------
        outputFilename : str
            filename to save this notebook to
        templateFilename : str, optional
            filename to build this notebook from (see save_to)
        '''
        self.save_to(outputFilename, templateFilename)
        outputFilename = _os.path.abspath(outputFilename)  # for path manips below

        from notebook import notebookapp
        servers = list(notebookapp.list_running_servers())
        for serverinfo in servers:
            rel = _os.path.relpath(outputFilename, serverinfo['notebook_dir'])
            if ".." not in rel:  # notebook servers don't allow moving up directories
                if port == 'auto' or int(serverinfo['port']) == port:
                    url = _os.path.join(serverinfo['url'], 'notebooks', rel)
                    _browser.open(url); break
        else:
            print("No running notebook server found that is rooted above %s" %
                  outputFilename) 
Example #4
Source File: auth_fitbit.py    From fitbit-googlefit with GNU General Public License v3.0 6 votes vote down vote up
def headless_authorize(self):
        """
        Authorize without a display using only TTY.
        """
        url, _ = self.oauth.authorize_token_url(redirect_uri=self.redirect_uri)
        # Ask the user to open this url on a system with browser
        print('\n-------------------------------------------------------------------------')
        print('\t\tOpen the below URL in your browser\n')
        print(url)
        print('\n-------------------------------------------------------------------------\n')
        print('NOTE: After authenticating on Fitbit website, you will redirected to a URL which ')
        print('throws an ERROR. This is expected! Just copy the full redirected here.\n')
        redirected_url = input('Full redirected URL: ')
        params = urlparse.parse_qs(urlparse.urlparse(redirected_url).query)
        print(params['code'][0])
        self.authenticate_code(code=params['code'][0]) 
Example #5
Source File: auth_fitbit.py    From fitbit-googlefit with GNU General Public License v3.0 6 votes vote down vote up
def main():
    # Arguments parsing
    parser = argparse.ArgumentParser("Client ID and Secret are mandatory arguments")
    parser.add_argument("-i", "--id", required=True, help="Client id", metavar='<client-id>')
    parser.add_argument("-s", "--secret", required=True, help="Client secret", 
        metavar='<client-secret>')
    parser.add_argument("-c", "--console", default=False, 
        help="Authenticate only using console (for headless systems)", action="store_true")
    args = parser.parse_args()

    server = OAuth2Server(args.id, args.secret)
    if args.console:
        server.headless_authorize()
    else:   
        server.browser_authorize()

    credentials = dict(
        client_id=args.id,
        client_secret=args.secret,
        access_token=server.oauth.token['access_token'],
        refresh_token=server.oauth.token['refresh_token'])
    json.dump(credentials, open('fitbit.json', 'w')) 
Example #6
Source File: ModelingCloth.py    From Modeling-Cloth with MIT License 6 votes vote down vote up
def collision_series(paperback=True, kindle=True):
    import webbrowser
    import imp
    if paperback:    
        webbrowser.open("https://www.createspace.com/6043857")
        imp.reload(webbrowser)
        webbrowser.open("https://www.createspace.com/7164863")
        return
    if kindle:
        webbrowser.open("https://www.amazon.com/Resolve-Immortal-Flesh-Collision-Book-ebook/dp/B01CO3MBVQ")
        imp.reload(webbrowser)
        webbrowser.open("https://www.amazon.com/Formulacrum-Collision-Book-Rich-Colburn-ebook/dp/B0711P744G")
        return
    webbrowser.open("https://www.paypal.com/donate/?token=G1UymFn4CP8lSFn1r63jf_XOHAuSBfQJWFj9xjW9kWCScqkfYUCdTzP-ywiHIxHxYe7uJW&country.x=US&locale.x=US")

# ============================================================================================ 
Example #7
Source File: RPSLS.py    From Python-Scripts-and-Games with MIT License 6 votes vote down vote up
def main():
    print('====== Menu ======')
    print('1. Play')
    print('2. See Source Code')
    print('3. Rules')
    print('4. Rules dictation by Sheldon Lee Cooper')
    print('5. Exit')
    inp = int(input('Enter Choice :'))
    if inp is 1:
        rpsls()
    elif inp is 3:
        rules()
    elif inp is 4:
        webbrowser.open('https://goo.gl/kR2653')
    elif inp is 5:
        exit()
    elif inp is 2:
        webbrowser.open('https://goo.gl/4TStoZ')
    if inp is not 5:
        main() 
Example #8
Source File: kegg.py    From bioservices with GNU General Public License v3.0 6 votes vote down vote up
def show_module(self, modId):
        """Show a given module inside a web browser

        :param str modId: a valid module Id. See :meth:`moduleIds`

        Validity of modId is not checked but if wrong the URL will not open a
        proper web page.
        """
        if modId.startswith("md:"):
            modId = modId.split(":")[1]
        url = "http://www.kegg.jp/module/" + modId
        self.logging.info(url)
        res = webbrowser.open(url)
        return res

    # wrapper of all databases to ease access to them (buffered) 
Example #9
Source File: ptinstaller.py    From pythonista-tools-installer with MIT License 6 votes vote down vote up
def install(self, url, target_folder):

        tmp_zipfile = self.download(url)
        base_dir = os.path.splitext(os.path.basename(tmp_zipfile))[0] + '/'
        with open(tmp_zipfile, 'rb') as ins:
            zipfp = zipfile.ZipFile(ins)
            for name in zipfp.namelist():
                data = zipfp.read(name)
                name = name.split(base_dir, 1)[-1]  # strip the top-level target_folder
                if name == '':  # skip top-level target_folder
                    continue

                fname = os.path.join(target_folder, name)
                if fname.endswith('/'):  # A target_folder
                    if not os.path.exists(fname):
                        os.makedirs(fname)
                else:
                    with open(fname, 'wb') as fp:
                        fp.write(data) 
Example #10
Source File: pydoc.py    From jawfish with MIT License 6 votes vote down vote up
def importfile(path):
    """Import a Python source file or compiled file given its path."""
    magic = imp.get_magic()
    with open(path, 'rb') as file:
        if file.read(len(magic)) == magic:
            kind = imp.PY_COMPILED
        else:
            kind = imp.PY_SOURCE
        file.seek(0)
        filename = os.path.basename(path)
        name, ext = os.path.splitext(filename)
        try:
            module = imp.load_module(name, file, path, (ext, 'r', kind))
        except:
            raise ErrorDuringImport(path, sys.exc_info())
    return module 
Example #11
Source File: window.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.init_window()
        
        self.about_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/LPHK-banner.png"))
        self.info_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/info.png"))
        self.warning_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/warning.png"))
        self.error_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/error.png"))
        self.alert_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/alert.png"))
        self.scare_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/scare.png"))
        self.grid_drawn = False
        self.grid_rects = [[None for y in range(9)] for x in range(9)]
        self.button_mode = "edit"
        self.last_clicked = None
        self.outline_box = None 
Example #12
Source File: client.py    From Jike-Metro with MIT License 6 votes vote down vote up
def open_in_browser(url_or_message):
        if isinstance(url_or_message, str):
            url = url_or_message
        elif hasattr(url_or_message, 'linkInfo'):
            url = url_or_message.linkInfo['linkUrl']
        elif 'linkInfo' in url_or_message:
            url = url_or_message['linkInfo']['linkUrl']
        elif hasattr(url_or_message, 'content'):
            urls = extract_url(url_or_message.content)
            if urls:
                for url in urls:
                    webbrowser.open(url)
                return
        else:
            raise ValueError('No url found')

        if not URL_VALIDATION_PATTERN.match(url):
            raise ValueError('Url invalid')
        else:
            webbrowser.open(url) 
Example #13
Source File: application.py    From sk1-wx with GNU General Public License v3.0 6 votes vote down vote up
def call_after(self, *args):
        if config.make_font_cache_on_start:
            font_cache_update()
        if self.docs:
            return
        docs = self._get_docs()
        if config.new_doc_on_start and not docs:
            self.load_plugins()
            self.new()
        else:
            txt = _('To start, create new document or open existing')
            events.emit(events.APP_STATUS, txt)
            self.load_plugins()
            if not wal.IS_WX2:
                events.emit(events.NO_DOCS)
        self.update_actions()
        for item in docs:
            self.open(item) 
Example #14
Source File: htmlvisitor.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def hinet_css(cls):
        """Return the standard CSS string.

        The CSS should be embedded in the final HTML file.
        """
        css_filename = os.path.join(os.path.split(__file__)[0],
                                    cls._CSS_FILENAME)
        with open(css_filename, 'r') as css_file:
            css = css_file.read()
        return css 
Example #15
Source File: pynpuzzle.py    From pynpuzzle with MIT License 5 votes vote down vote up
def update_logs_text_if_visible():
    """
    If show logs window is open, then update the text widget's content.
    If someone updates app logs, then should invoke this function.
    """
    if logs_text:
        logs_text['state'] = tkinter.NORMAL
        logs_text.delete(0.0, tkinter.END)
        logs_text.insert(0.0, ''.join(LOGS))
        logs_text['state'] = tkinter.DISABLED
        # Scroll to end of text
        logs_text.see(tkinter.END) 
Example #16
Source File: dpUtils.py    From dpAutoRigSystem with GNU General Public License v2.0 5 votes vote down vote up
def visitWebSite(website, *args):
    """ Start browser with the given website address.
    """
    #webSiteString = "start "+website
    #os.popen(webSiteString)
    webbrowser.open(website, new=2) 
Example #17
Source File: application.py    From sk1-wx with GNU General Public License v3.0 5 votes vote down vote up
def open_url(self, url):
        webbrowser.open(url, new=1, autoraise=True)
        msg = _('Requested page was opened in the default browser')
        events.emit(events.APP_STATUS, msg) 
Example #18
Source File: application.py    From sk1-wx with GNU General Public License v3.0 5 votes vote down vote up
def close(self, doc=None):
        if not self.docs:
            return
        doc = doc or self.current_doc

        if self.insp.is_doc_not_saved(doc):
            if not doc == self.current_doc:
                self.set_current_doc(doc)

            msg = _("Document '%s' has been modified.") % doc.doc_name + '\n'
            msg += _('Do you want to save your changes?')
            ret = dialogs.ync_dialog(self.mw, self.appdata.app_name, msg)

            if ret is None:
                return False
            if ret:
                if not self.save():
                    return False

        if doc in self.docs:
            index = self.docs.index(doc)
            active = doc == self.current_doc
            self.docs.remove(doc)
            self.mdi.remove_doc(doc)
            doc.close()
            events.emit(events.DOC_CLOSED)
            if not len(self.docs):
                self.current_doc = None
                self.mw.show_mdi(False)
                events.emit(events.NO_DOCS)
                msg = _('To start, create new document or open existing')
                events.emit(events.APP_STATUS, msg)
                self.mw.set_title()
            elif active:
                index = index if len(self.docs) > index else -1
                self.set_current_doc(self.docs[index])
        return True 
Example #19
Source File: application.py    From sk1-wx with GNU General Public License v3.0 5 votes vote down vote up
def open(self, doc_file='', silent=False):
        doc_file = doc_file or \
                   dialogs.get_open_file_name(self.mw, config.open_dir)
        if doc_file and fsutils.isfile(doc_file):
            try:
                doc = SK1Presenter(self, doc_file, silent)

            except RuntimeError:
                msg = _('Cannot open file:')
                msg = "%s\n'%s'" % (msg, doc_file) + '\n'
                msg += _('The file contains newer SK2 format.\n')
                msg += _('Try updating sK1 application from '
                         'https://sk1project.net')
                dialogs.error_dialog(self.mw, self.appdata.app_name, msg)
                LOG.error('Cannot open file <%s>: newer SK2 format.', doc_file)
                return
            except Exception as e:
                msg = _('Cannot open file:')
                msg = "%s\n'%s'" % (msg, doc_file) + '\n'
                msg += _('The file may be corrupted or not supported format')
                msg += '\n'
                msg += _('Details see in application logs.')
                dialogs.error_dialog(self.mw, self.appdata.app_name, msg)
                LOG.error('Cannot open file <%s> %s', doc_file, e, exc_info=True)
                return
            self.docs.append(doc)
            config.open_dir = str(os.path.dirname(doc_file))
            self.history.add_entry(doc_file)
            self.set_current_doc(doc)
            events.emit(events.APP_STATUS, _('Document opened')) 
Example #20
Source File: ipip.py    From scripts with MIT License 5 votes vote down vote up
def save_cookie(driver):
    pickle.dump(driver.get_cookies(), open(PATH_COOKIE + "cookies.pkl", "wb")) 
Example #21
Source File: slideshow.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def basic_css():
    """Return the basic default CSS."""
    css_filename = os.path.join(os.path.split(__file__)[0],
                                _BASIC_CSS_FILENAME)
    with open(css_filename, 'r') as css_file:
        css = css_file.read()
    return css 
Example #22
Source File: tasks.py    From NeuroKit with MIT License 5 votes vote down vote up
def coverage(c, publish=False):
    """
    Create coverage report
    """
    c.run("coverage run --source {} -m pytest".format(SOURCE_DIR))
    c.run("coverage report")
    if publish:
        # Publish the results via coveralls
        c.run("coveralls")
    else:
        # Build a local report
        c.run("coverage html")
        webbrowser.open(COVERAGE_REPORT.as_uri()) 
Example #23
Source File: slideshow.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def slideshow_css():
    """Return the additional CSS for a slideshow."""
    css_filename = os.path.join(os.path.split(__file__)[0],
                                _SLIDESHOW_CSS_FILENAME)
    with open(css_filename, 'r') as css_file:
        css = css_file.read()
    return css 
Example #24
Source File: htmlvisitor.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def show_flow(flow, filename=None, title="MDP flow display",
              show_size=False, browser_open=True):
    """Write a flow into a HTML file, open it in the browser and
    return the file name.

    flow -- The flow to be shown.
    filename -- Filename for the HTML file to be created. If None
                a temporary file is created.
    title -- Title for the HTML file.
    show_size -- Show the approximate memory footprint of all nodes.
    browser_open -- If True (default value) then the slideshow file is
        automatically opened in a webbrowser.
    """
    if filename is None:
        (fd, filename) = tempfile.mkstemp(suffix=".html", prefix="MDP_")
        html_file = os.fdopen(fd, 'w')
    else:
        html_file = open(filename, 'w')
    html_file.write('<html>\n<head>\n<title>%s</title>\n' % title)
    html_file.write('<style type="text/css" media="screen">')
    html_file.write(mdp.utils.basic_css() + HiNetHTMLVisitor.hinet_css())
    html_file.write('</style>\n</head>\n<body>\n')
    html_file.write('<h3>%s</h3>\n' % title)
    explanation = '(data flows from top to bottom)'
    html_file.write('<par class="explanation">%s</par>\n' % explanation)
    html_file.write('<br><br><br>\n')
    converter = mdp.hinet.HiNetHTMLVisitor(html_file, show_size=show_size)
    converter.convert_flow(flow=flow)
    html_file.write('</body>\n</html>')
    html_file.close()
    if browser_open:
        webbrowser.open(os.path.abspath(filename))
    return filename 
Example #25
Source File: test_runner.py    From Zopkio with Apache License 2.0 5 votes vote down vote up
def _display_results(self):
    """
    Displays the report in a web page

    :return:
    """
    webbrowser.open("file://" + self.reporter.get_report_location()) 
Example #26
Source File: notebook.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def add_notebook_file(self, filename):
        '''
        Append an .ipynb file to this notebook

        Parameters
        ----------
        filename : str
            ipynb file to append
        '''
        with open(str(filename), 'r') as infile:
            notebookDict = _json.load(infile)
        for cell in notebookDict['cells']:
            self.add(NotebookCell(cell['cell_type'], cell['source'])) 
Example #27
Source File: merge_helpers.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def read_contents(filename):
    """
    Read the contents from `filename` as a string.

    Parameters
    ----------
    filename : str

    Returns
    -------
    str
    """
    contents = None
    try:  # on Windows using python3 open can fail when trying to read text files. encoding fixes this
        f = open(str(filename))
        contents = f.read()
    except UnicodeDecodeError:
        f = open(str(filename), encoding='utf-8')  # try this, but not available in python 2.7!
        contents = f.read()

    f.close()

    try:  # to convert to unicode since we use unicode literals
        contents = contents.decode('utf-8')
    except AttributeError: pass  # Python3 case when unicode is read in natively (no need to decode)

    return contents 
Example #28
Source File: notebook.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def to_json_dict(self, templateFilename=DefaultTemplate):
        '''
        Using an existing (usually empty) notebook as a template, generate the json for a new notebook.

        Parameters
        ----------
        templateFilename : str, optional
            Name of an existing notebook file to build from
        '''
        templateFilename = _os.path.join(_os.path.dirname(_os.path.abspath(__file__)),
                                         'templates', templateFilename)
        with open(str(templateFilename), 'r') as infile:
            notebookDict = _json.load(infile)
        notebookDict['cells'].extend([c.to_json_dict() for c in self.cells])
        return notebookDict 
Example #29
Source File: notebook.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def add_notebook_text_file(self, filename):
        '''
        Add a custom formatted text file to the notebook
        Text file contains both python and markdown, with
        cells differentiated by @@code and @@markdown tags.
        At least one cell tag must be present for the file to be correctly parsed

        Parameters
        ----------
        filename : str
            name of file containing notebook formatted text
        '''
        with open(str(filename), 'r') as infile:
            self.add_notebook_text(infile.read()) 
Example #30
Source File: notebook.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def save_to(self, outputFilename, templateFilename=DefaultTemplate):
        '''
        Save this class to a file as a jupyter notebook

        Parameters
        ----------
        outputFilename : str
            File to save the output jupyter notebook to

        templateFilename : str, optional
            Name of an existing notebook file to build from
        '''
        jsonDict = self.to_json_dict(templateFilename)
        with open(str(outputFilename), 'w') as outfile:
            _json.dump(jsonDict, outfile)