Python webbrowser 模块,open() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webbrowser.open()

项目:Freya    作者:areebbeigh    | 项目源码 | 文件源码
def play_music(p, l):
    """ Plays music """
    respond("playing music", prepend_positive_response=True)
    playlist = os.path.join(BASE_DIRECTORY, 'playlist.m3u')

    extensions = [
        ".mp3",
        ".m4a",
        ".ogg",
        ".flac",
    ]

    music_files = _get_all_files(preferences.get_music_dir(), extensions)

    with open(playlist, 'w') as f:
        for file in music_files:
            f.write(file + "\n")

    os.startfile(playlist)
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
def execute(self, context):
        #self.link = self.link.replace(" ","%")
        #webbrowser.open("https://twitter.com/intent/tweet?text=Check%out%#2DAnimTools%by%@ndee85")

        url = "https://twitter.com/intent/tweet?"
        if self.link != "":
            url += "&url="+self.link
        if self.text != "":    
            url += "&text="+self.text.replace(" ","+")
        if self.hashtags != "":    
            url += "&hashtags="+self.hashtags
        if self.via != "":
            url += "&via="+self.via
        #"https://twitter.com/intent/tweet?url=https://www.youtube.com/ndee85&text=Hello+World&hashtags=coatools,test&via=ndee85"    
        webbrowser.open(url)
        return {"FINISHED"}
项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def show_about(self):
        def events_callback(instance_label, text_link):
            def answer_callback(answer):
                if answer in [core.string_lang_click_dimonvideo_redirect,
                              core.string_lang_click_ptyhon_redirect,
                              core.string_lang_click_kivy_redirect]:
                    webbrowser.open(answer.replace("www.", r"http:\\"))

            if text_link in ["HeaTTheatR", "Virtuos86", "dimy44"]:
                Clock.schedule_once(
                    lambda *args: self.send_mail_or_show_profile(text_link),
                    0.1)
            else:
                self.create_window(
                    callback=answer_callback, param="query",
                    text=core.text_for_about[text_link]["text"],
                    button_ok=core.text_for_about[text_link]["ok"],
                    button_cancel=core.text_for_about[text_link]["cancel"])

        AboutDialog(events_callback=events_callback,
                    background_image=core.theme_decorator_window,
                    name_program=core.string_lang_about_name_program,
                    logo_program="Data/Images/logo.png",
                    info_program=core.info_program)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def synopsis(filename, cache={}):
    """Get the one-line summary out of a module file."""
    mtime = os.stat(filename).st_mtime
    lastupdate, result = cache.get(filename, (0, None))
    if lastupdate < mtime:
        info = inspect.getmoduleinfo(filename)
        try:
            file = open(filename)
        except IOError:
            # module can't be opened, so skip it
            return None
        if info and 'b' in info[2]: # binary modules have to be imported
            try: module = imp.load_module('__temp__', file, filename, info[1:])
            except: return None
            result = (module.__doc__ or '').splitlines()[0]
            del sys.modules['__temp__']
        else: # text modules can be directly examined
            result = source_synopsis(file)
            file.close()
        cache[filename] = (mtime, result)
    return result
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def importfile(path):
    """Import a Python source file or compiled file given its path."""
    magic = imp.get_magic()
    file = open(path, 'r')
    if file.read(len(magic)) == magic:
        kind = imp.PY_COMPILED
    else:
        kind = imp.PY_SOURCE
    file.close()
    filename = os.path.basename(path)
    name, ext = os.path.splitext(filename)
    file = open(path, 'r')
    try:
        module = imp.load_module(name, file, path, (ext, 'r', kind))
    except:
        raise ErrorDuringImport(path, sys.exc_info())
    file.close()
    return module
项目:whatstyle    作者:mikr    | 项目源码 | 文件源码
def reformat(self, sourcefile, destfile, configfile):
        # type: (str, str, str) -> None
        formatstyle = style_make()
        with open(configfile) as fp:
            for line in fp.readlines():
                line = line.rstrip()
                if line.startswith('--'):
                    line = line[2:]
                    pos = line.find('=')
                    if pos > 0:
                        optionname, value = line[:pos], line[pos + 1:]
                    else:
                        optionname, value = line, OPTION_PRESENT
                    set_option(formatstyle, optionname, value)
        sourcedata = readbinary(sourcefile)
        data = self.formatcode(formatstyle, sourcedata, filename=sourcefile)
        if data is None:
            data = b''
        writebinary(destfile, data)

# ----------------------------------------------------------------------
项目:whatstyle    作者:mikr    | 项目源码 | 文件源码
def reformat(self, sourcefile, destfile, configfile):
        # type: (str, str, str) -> None
        formatstyle = style_make()
        with open(configfile) as fp:
            for line in fp.readlines():
                line = line.rstrip()
                if line.startswith('#'):
                    continue
                parts = line.split('=')
                if len(parts) == 2:
                    optionname, value = parts
                    set_option(formatstyle, optionname, value)
        sourcedata = readbinary(sourcefile)
        data = self.formatcode(formatstyle, sourcedata, filename=sourcefile)
        if data is None:
            data = b''
        writebinary(destfile, data)

# ----------------------------------------------------------------------
项目:whatstyle    作者:mikr    | 项目源码 | 文件源码
def reformat(self, sourcefile, destfile, configfile):
        # type: (str, str, str) -> None
        formatstyle = style_make()
        with open(configfile) as fp:
            for line in fp.readlines():
                line = line.rstrip()
                if line.startswith('#'):
                    continue
                parts = re.split(r'\s+=\s+', line)
                if len(parts) == 2:
                    optionname, value = parts
                    set_option(formatstyle, optionname, value)
        sourcedata = readbinary(sourcefile)
        data = self.formatcode(formatstyle, sourcedata, filename=sourcefile)
        if data is None:
            data = b''
        writebinary(destfile, data)

# ----------------------------------------------------------------------
# Functions for the in-memory cache
项目:ISM2017    作者:ybayle    | 项目源码 | 文件源码
def read_train_files(indir, separator=" "):
    """Description of read_train_files

    Gather local features and GT from every individual train songs
    """
    utils.print_success("Reading multiple train files")
    indir = utils.abs_path_dir(indir) + "/"
    groundtruths = []
    features = []
    included_extenstions = ["csv"]
    filenames = [fn for fn in os.listdir(indir)
            if any(fn.endswith(ext) for ext in included_extenstions)]
    for index, filename in enumerate(filenames):
        print(str(index + 1) + "/" + str(len(filenames)) + " " + filename)
        sys.stdout.write("\033[F") # Cursor up one line       
        sys.stdout.write("\033[K") # Clear line
        with open(indir + filename, "r") as filep:
            for row in filep:
                line = row.split(separator)
                features.append([float(i) for i in line[:-1]])
                groundtruths.append(line[-1][:-1])
    sys.stdout.write("\033[K") # Clear line
    return features, groundtruths
项目:ISM2017    作者:ybayle    | 项目源码 | 文件源码
def read_test_file(filename):
    """
    Read ONE test file with content like:

        feat1 feat2 ... featN
        feat1 feat2 ... featN
        ...
        feat1 feat2 ... featN

    """
    features = []
    filename = utils.abs_path_file(filename)
    with open(filename, "r") as filep:
        for line in filep:
            line = line.split(" ")
            line[-1] = line[-1][:-1]
            feat = []
            for tmp_feat in line:
                feat.append(float(tmp_feat))
            features.append(feat)
    return features
项目:ISM2017    作者:ybayle    | 项目源码 | 文件源码
def test_models(models_dir, test_dir, out_dir):
    models_dir = utils.abs_path_dir(models_dir) + "/"
    test_dir = utils.abs_path_dir(test_dir) + "/"
    utils.create_dir(out_dir)
    test_files = os.listdir(test_dir)
    models = os.listdir(models_dir)
    for model in models:
        utils.print_success(model)
        pred_dir = out_dir + model + "/"
        utils.create_dir(pred_dir)
        clf = joblib.load(models_dir + model + "/" + model + ".pkl")
        for index, test_file in enumerate(test_files):
            print(str(index) + "\t" + test_file)
            sys.stdout.write("\033[F")
            sys.stdout.write("\033[K")
            test_features = read_test_file(test_dir + test_file)
            predictions = clf.predict_proba(test_features)
            with open(pred_dir + test_file, "w") as filep:
                for pred in predictions:
                    filep.write(str(pred[0]) + "\n")
        sys.stdout.write("\033[K")
项目:BioNanoAnalyst    作者:AppliedBioinformatics    | 项目源码 | 文件源码
def handle_ref_error(self):
        try:
            if os.stat(self.ref).st_size>0:
                with open(self.ref) as f:
                    for i in range(2):
                        line=f.next().strip()
                        if i == 0 and line[0]!='>':
                            return QtGui.QMessageBox.question(self, 'Error !', 'Please check your input reference !',
                            QtGui.QMessageBox.Ok)
                        if i == 1 and len(re.findall("[^ATGCN]", line.upper()))>0:
                            return QtGui.QMessageBox.question(self, 'Error !', 'Please check your input reference !',
                            QtGui.QMessageBox.Ok)
            else:
                return QtGui.QMessageBox.question(self, 'Warning !', 'The selected reference file is empty, please check !',
                QtGui.QMessageBox.Ok)
        except:
            return QtGui.QMessageBox.question(self, 'Error !', 'Please input a reference file !',
            QtGui.QMessageBox.Ok)
项目:engel    作者:Dalloriam    | 项目源码 | 文件源码
def start(self, callback=None):
        self.loop.run_until_complete(self.server)

        try:
            path = os.path.dirname(os.path.realpath(__file__))
            webbrowser.open('file:///' + os.path.join(path, 'index.html'))
            self.loop.run_forever()

        except KeyboardInterrupt:
            pass

        finally:
            self.server.close()
            self.loop.close()

            if callback is not None and callable(callback):
                callback()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def main(cls, RequestHandlerClass, port=80):
        """Start server with handler on given port.

        This static method provides an easy way to start, run, and exit
        a HttpServer instance. The server will be executed if possible,
        and the computer's web browser will be directed to the address."""
        try:
            server = cls(('', port), RequestHandlerClass)
            active = True
        except socket.error:
            active = False
        else:
            addr, port = server.socket.getsockname()
            print('Serving HTTP on', addr, 'port', port, '...')
        finally:
            port = '' if port == 80 else ':' + str(port)
            addr = 'http://localhost' + port + '/'
            webbrowser.open(addr)
        if active:
            try:
                server.serve_forever()
            except KeyboardInterrupt:
                print('Keyboard interrupt received: EXITING')
            finally:
                server.server_close()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def get_settings(self):
        # Try opening and loading the settings from file.
        filename = os.path.join(self.__path, self.FILENAME)
        try:
            with open(filename, 'rb') as file:
                settings = pickle.load(file)
            # Test the pickle and check each setting inside it.
            assert isinstance(settings, dict)
            key_list = list(self.DEFAULT)
            for key in settings:
                assert isinstance(key, str)
                assert key in self.DEFAULT
                key_list.remove(key)
            # Add new settings as needed (when new ones are created).
            for key in key_list:
                settings[key] = self.DEFAULT[key]
            # Return old settings, or on error, the default settings.
            return False, settings
        except (IOError, pickle.UnpicklingError, AssertionError):
            return True, self.DEFAULT
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def update(self, callback):
        # Find out if the file has been modified.
        modified = os.path.getmtime(self.__path)
        if modified != self.__modified:
            # Remember the present time (we are getting an update).
            self.__modified = modified
            with open(self.__path, 'r') as file:
                # Go to present location, read to EOF, and remember position.
                file.seek(self.__position)
                try:
                    text = file.read()
                except UnicodeError:
                    print('Please report problem with:', repr(self.__path))
                    traceback.print_exc()
                    print('-' * 80)
                self.__position = file.tell()
            # Execute callback with file ID and new text update.
            callback(self.__path, text)

################################################################################
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
def getchar(echo):
        if not isatty(sys.stdin):
            f = open('/dev/tty')
            fd = f.fileno()
        else:
            fd = sys.stdin.fileno()
            f = None
        try:
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(fd)
                ch = os.read(fd, 32)
                if echo and isatty(sys.stdout):
                    sys.stdout.write(ch)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
                sys.stdout.flush()
                if f is not None:
                    f.close()
        except termios.error:
            pass
        _translate_ch_to_exc(ch)
        return ch.decode(get_best_encoding(sys.stdin), 'replace')
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def body(self, master):
        self.t = Text(master)
        self.t.pack()
        self.t.tag_configure("href", foreground='blue', underline=1)
        self.t.tag_bind("href", "<Button-1>", self.openHREF)
        self.t.tag_bind("href", "<Enter>", self.show_hand_cursor)
        self.t.tag_bind("href", "<Leave>", self.show_arrow_cursor)
        self.t.config(cursor="arrow", bg="SystemButtonFace", wrap=WORD)
        self.t.insert(END, "Thank you for using PyKeylogger, a versatile backup and system monitoring solution.")
        self.t.insert(END, "\n\nAs you may remember from reading the \"welcome screen\", this binary expires \
after 4 days of use, as a method of encouraging donations to this open source software project. This installation of \
PyKeylogger has now *EXPIRED*. There are two ways \
to restore PyKeylogger's functionality: \n\n 1. Donate to PyKeylogger by following the simple instructions at ")
        self.t.insert(END, "http://pykeylogger.sourceforge.net/wiki/index.php/PyKeylogger:Download_Instructions", "href")
        self.t.insert(END, " and you will get a binary build of PyKeylogger without any nagscreens or expiration, \
by E-mail, HTTP, or FTP.")
        self.t.insert(END, "\n\n 2. Get the source code, then find and toggle the nag control. You can then run \
PyKeylogger from source, or even build your own executable, by following the instructions at ")
        self.t.insert(END, "http://pykeylogger.sourceforge.net/wiki/index.php/PyKeylogger:Installation_Instructions", "href")
        self.t.insert(END, "\n\nIf you run into any trouble, feel free to ask for help on the PyKeylogger forums: ")
        self.t.insert(END, "http://sourceforge.net/forum/?group_id=147501", "href")
        self.t.config(state=DISABLED)
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def recaptcha(self):
        """ Check if we need to solve a captcha.

        This will open in the default browser.

        If we choose to not solve the captcha should it be required,
        we will then be considered a 'lurker' and we will not be able to chat
        and our name will be shown as a guest name in the room.
        """
        t = str(random.uniform(0.9, 0.10))
        _url = 'https://tinychat.com/cauth/captcha?{0}'.format(t)

        _response = util.web.http_get(url=_url, json=True, proxy=self.proxy)
        log.debug('recaptcha response: %s' % _response)
        if _response['json'] is not None:
            if _response['json']['need_to_solve_captcha'] == 1:
                link = 'https://tinychat.com/cauth/recaptcha?token={0}'.format(_response['json']['token'])
                webbrowser.open(link, new=True)
                print (link)
                raw_input('Solve the captcha and click enter to continue.')
项目:ggbackup    作者:lindegroup    | 项目源码 | 文件源码
def first_auth(self, client_secrets):
        """Authenticate with Google API."""
        flow = client.flow_from_clientsecrets(
            client_secrets,
            scope=[
                'https://www.googleapis.com/auth/admin.directory.group.readonly',  # noqa
                'https://www.googleapis.com/auth/admin.directory.group.member.readonly',  # noqa
                'https://www.googleapis.com/auth/apps.groups.settings'
            ],
            redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        logger.debug('Generating authorization URL.')
        auth_uri = flow.step1_get_authorize_url()
        webbrowser.open(auth_uri)

        auth_code = input('Enter the auth code: ')

        logger.debug('Generating credentials.')
        self.credentials = flow.step2_exchange(auth_code)
项目:PhaserSublimePackage    作者:PhaserEditor2D    | 项目源码 | 文件源码
def server_port(project, ignored=None):
  if project.port is not None and project.port != ignored:
    return (project.port, True)
  if project.port == ignored:
    kill_server(project)

  port_file = os.path.join(project.dir, ".tern-port")
  if os.path.isfile(port_file):
    port = int(open(port_file, "r").read())
    if port != ignored:
      project.port = port
      return (port, True)

  started = start_server(project)
  if started is not None:
    project.port = started
  return (started, False)
项目:PhaserSublimePackage    作者:PhaserEditor2D    | 项目源码 | 文件源码
def run(self, edit, **args):
    data = run_command(self.view, {"type": "definition", "lineCharPositions": True})
    if data is None: return
    file = data.get("file", None)
    if file is not None:
      # Found an actual definition
      row, col = self.view.rowcol(self.view.sel()[0].b)
      cur_pos = self.view.file_name() + ":" + str(row + 1) + ":" + str(col + 1)
      jump_stack.append(cur_pos)
      if len(jump_stack) > 50: jump_stack.pop(0)
      real_file = (os.path.join(get_pfile(self.view).project.dir, file) +
        ":" + str(data["start"]["line"] + 1) + ":" + str(data["start"]["ch"] + 1))
      sublime.active_window().open_file(real_file, sublime.ENCODED_POSITION)
    else:
      url = data.get("url", None)
      if url is None:
        sublime.error_message("Could not find a definition")
      else:
        webbrowser.open(url)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def synopsis(filename, cache={}):
    """Get the one-line summary out of a module file."""
    mtime = os.stat(filename).st_mtime
    lastupdate, result = cache.get(filename, (None, None))
    if lastupdate is None or lastupdate < mtime:
        info = inspect.getmoduleinfo(filename)
        try:
            file = open(filename)
        except IOError:
            # module can't be opened, so skip it
            return None
        if info and 'b' in info[2]: # binary modules have to be imported
            try: module = imp.load_module('__temp__', file, filename, info[1:])
            except: return None
            result = (module.__doc__ or '').splitlines()[0]
            del sys.modules['__temp__']
        else: # text modules can be directly examined
            result = source_synopsis(file)
            file.close()
        cache[filename] = (mtime, result)
    return result
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def importfile(path):
    """Import a Python source file or compiled file given its path."""
    magic = imp.get_magic()
    file = open(path, 'r')
    if file.read(len(magic)) == magic:
        kind = imp.PY_COMPILED
    else:
        kind = imp.PY_SOURCE
    file.close()
    filename = os.path.basename(path)
    name, ext = os.path.splitext(filename)
    file = open(path, 'r')
    try:
        module = imp.load_module(name, file, path, (ext, 'r', kind))
    except:
        raise ErrorDuringImport(path, sys.exc_info())
    file.close()
    return module
项目:NetworkScraper    作者:RLesser    | 项目源码 | 文件源码
def basicWebServer(self):
        import SimpleHTTPServer
        import SocketServer

        PORT = 8000

        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

        while (True):
            try:
                print "Trying to open on port", PORT
                httpd = SocketServer.TCPServer(("", PORT), Handler)
            except Exception as e:
                print "port", PORT, "did not work, checking next port"
                PORT += 1
            else:
                break

        print "serving at port", PORT
        webbrowser.open("http://localhost:"+str(PORT)+"/forceD3/force.html")
        httpd.serve_forever()



    ### FUNCTIONS TO BE DEFINED IN SUBCLASSES ###
项目:NetworkScraper    作者:RLesser    | 项目源码 | 文件源码
def graphD3(self, buds_visible = False, filter_assym_edges = False):
        # possibly combine with above?
        self.buds_visible = buds_visible
        self.filter_assym_edges = filter_assym_edges
        G = self.makeGraphData(mode = "d3")
        # print G
        if hasattr(self, 'nodeColorInfo'):
            G = self.useColorData(G, "d3")
        # for item in adjList:
        #   print item
        #nodeColors = self.useColorData(G)
        #for item in nx.readwrite.__dict__:
            #print item
        # nodeLinkData = nx.readwrite.d3_js(G)
        #print G
        json.dump(G, open('forceD3/force.json','w'))
        self.basicWebServer()
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def openFile(filename, mode=u'rU', continueOnError=False, displayError=True):
  try:
    if filename != u'-':
      return open(os.path.expanduser(filename), mode)
    if mode.startswith(u'r'):
      return StringIOobject(text_type(sys.stdin.read()))
    return sys.stdout
  except IOError as e:
    if continueOnError:
      if displayError:
        stderrWarningMsg(e)
        setSysExitRC(FILE_ERROR_RC)
      return None
    systemErrorExit(FILE_ERROR_RC, e)

# Close a file
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def readFile(filename, mode=u'rU', continueOnError=False, displayError=True, encoding=None):
  try:
    if filename != u'-':
      if not encoding:
        with open(os.path.expanduser(filename), mode) as f:
          return f.read()
      with codecs.open(os.path.expanduser(filename), mode, encoding) as f:
        content = f.read()
# codecs does not strip UTF-8 BOM (ef:bb:bf) so we must
        if not content.startswith(codecs.BOM_UTF8):
          return content
        return content[3:]
    return text_type(sys.stdin.read())
  except IOError as e:
    if continueOnError:
      if displayError:
        stderrWarningMsg(e)
        setSysExitRC(FILE_ERROR_RC)
      return None
    systemErrorExit(FILE_ERROR_RC, e)
  except (LookupError, UnicodeDecodeError, UnicodeError) as e:
    Cmd.Backup()
    usageErrorExit(e)

# Write a file
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def getchar(echo):
        if not isatty(sys.stdin):
            f = open('/dev/tty')
            fd = f.fileno()
        else:
            fd = sys.stdin.fileno()
            f = None
        try:
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(fd)
                ch = os.read(fd, 32)
                if echo and isatty(sys.stdout):
                    sys.stdout.write(ch)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
                sys.stdout.flush()
                if f is not None:
                    f.close()
        except termios.error:
            pass
        _translate_ch_to_exc(ch)
        return ch.decode(get_best_encoding(sys.stdin), 'replace')
项目:Modeling-Cloth    作者:the3dadvantage    | 项目源码 | 文件源码
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")

# ============================================================================================
项目:B.E.N.J.I.    作者:the-ethan-hunt    | 项目源码 | 文件源码
def removePastReminders(self):
        try :
            file_hand = open(reminder_filename, 'r')
            reminder_list = file_hand.readlines()
            file_hand.close()
            new_list = list()
            for reminder in reminder_list :
                date_time = datetime.strptime(reminder.split('\t')[1].replace('\n',''), '%d %b %Y %I %M %p')
                time_diff = date_time - datetime.now()
                if time_diff.seconds >= 0 and time_diff.days >= 0 :
                    new_list.append(reminder)
            file_hand = open(reminder_filename, 'w')
            for line in new_list :
                file_hand.write(line)
            file_hand.close()
        except FileNotFoundError :
            pass
        except :
            self.frame.displayText("Error occured")
项目:Wechat-tool-for-USC-Second-hand-Group    作者:tonnkie    | 项目源码 | 文件源码
def send_msg(self, name, word, isfile=False):
        uid = self.get_user_id(name)
        if uid is not None:
            if isfile:
                with open(word, 'r') as f:
                    result = True
                    for line in f.readlines():
                        line = line.replace('\n', '')
                        print '-> ' + name + ': ' + line
                        if self.send_msg_by_uid(line, uid):
                            pass
                        else:
                            result = False
                        time.sleep(1)
                    return result
            else:
                word = self.to_unicode(word)
                if self.send_msg_by_uid(word, uid):
                    return True
                else:
                    return False
        else:
            if self.DEBUG:
                print '[ERROR] This user does not exist .'
            return True
项目:Wechat-tool-for-USC-Second-hand-Group    作者:tonnkie    | 项目源码 | 文件源码
def get_icon(self, uid, gid=None):
        """
        ?????????????
        :param uid: ???id
        :param gid: ?id?????None????????????None????????
        """
        if gid is None:
            url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
        else:
            url = self.base_uri + '/webwxgeticon?username=%s&skey=%s&chatroomid=%s' % (
            uid, self.skey, self.encry_chat_room_id_list[gid])
        r = self.session.get(url)
        data = r.content
        fn = 'icon_' + uid + '.jpg'
        with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
            f.write(data)
        return fn
项目:kcli    作者:karmab    | 项目源码 | 文件源码
def update_repo(self, name, url=None):
        reposfile = "%s/.kcli/repos.yml" % os.environ.get('HOME')
        repodir = "%s/.kcli/repo_%s" % (os.environ.get('HOME'), name)
        if url is None:
            if not os.path.exists(reposfile) or os.path.getsize(reposfile) == 0:
                common.pprint("Empty .kcli/repos.yml. Leaving...", color='red')
                sys.exit(1)
            else:
                with open(reposfile, 'r') as entries:
                    try:
                        repos = yaml.load(entries)
                    except yaml.scanner.ScannerError:
                        common.pprint("Couldn't properly parse .kcli/repos.yml. Leaving...", color='red')
                        sys.exit(1)
                if name not in repos:
                    common.pprint("Entry for name allready there. Leaving...", color='red')
                    sys.exit(1)
            url = "%s/KMETA" % repos[name]
        elif 'KMETA' not in url:
            url = "%s/KMETA" % url
        common.fetch(url, repodir)
        return {'result': 'success'}
项目:loco    作者:kootenpv    | 项目源码 | 文件源码
def public_port_exists(rline, authorized_keys_file, restrictions, public_key, port):
    port = str(port)
    new_restrictions = []
    replaced = False
    for restriction in restrictions.split("\n"):
        if public_key in restriction:
            if ":" + port + '"' not in restriction:
                new_opens = 'no-pty,permitopen="localhost:{0}",permitopen="127.0.0.1:{0}",'
                restriction = restriction.replace("no-pty,", new_opens.format(port))
                replaced = True
            else:
                print("public_key and port already exists in", authorized_keys_file)
                return
        new_restrictions.append(restriction)
    print("Adding key+port rule to file")
    if replaced:
        result = "\n".join(new_restrictions)
    else:
        result = rline
    with open(authorized_keys_file, "w") as f:
        f.write(result + "\n")
项目:furi-kura    作者:benjamindean    | 项目源码 | 文件源码
def build_login_menu(self):

        def open_login(context):
            webbrowser.open(self.cfg_cls.LOGIN_URI, new=1, autoraise=True)

        login_menu = Gtk.Menu()
        item_login = Gtk.MenuItem('Login')
        item_separator = Gtk.SeparatorMenuItem()
        item_quit = Gtk.MenuItem('Quit')

        item_login.connect('activate', open_login)
        item_quit.connect('activate', self.quit)

        login_menu.append(item_login)
        login_menu.append(item_separator)
        login_menu.append(item_quit)
        login_menu.show_all()

        self.INDICATOR.set_menu(login_menu)
项目:dingdang-robot    作者:wzpan    | 项目源码 | 文件源码
def send_msg(self, name, word, isfile=False):
        uid = self.get_user_id(name)
        if uid is not None:
            if isfile:
                with open(word, 'r') as f:
                    result = True
                    for line in f.readlines():
                        line = line.replace('\n', '')
                        print '-> ' + name + ': ' + line
                        if self.send_msg_by_uid(line, uid):
                            pass
                        else:
                            result = False
                        time.sleep(1)
                    return result
            else:
                word = self.to_unicode(word)
                if self.send_msg_by_uid(word, uid):
                    return True
                else:
                    return False
        else:
            if self.DEBUG:
                print '[ERROR] This user does not exist .'
            return True
项目:dingdang-robot    作者:wzpan    | 项目源码 | 文件源码
def get_icon(self, uid, gid=None):
        """
        ?????????????
        :param uid: ???id
        :param gid: ?id?????None????????????None????????
        """
        if gid is None:
            url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
        else:
            url = self.base_uri + '/webwxgeticon?username=%s&skey=%s&chatroomid=%s' % (
            uid, self.skey, self.encry_chat_room_id_list[gid])
        r = self.session.get(url)
        data = r.content
        fn = 'icon_' + uid + '.jpg'
        with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
            f.write(data)
        return fn
项目:fitbit-googlefit    作者:praveendath92    | 项目源码 | 文件源码
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])
项目:fitbit-googlefit    作者:praveendath92    | 项目源码 | 文件源码
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'))
项目:torrent-hound    作者:baddymaster    | 项目源码 | 文件源码
def print_menu(arg=0):
    if arg == 0:
        print '''
        ------ Help Menu -------
        Available Commands :
        1. m<result number> - Print magnet link of selected torrent
        2. c<result number> - Copy magnet link of selected torrent to clipboard
        3. d<result number> - Download torrent using default torrent client
        4. o<result number> - Open the torrent page of the selected torrent in the default browser
        5. cs<result number> - Copy magnet link and open seedr.cc
        6. cz<result number> - Copy magnet link and open zbigz
        7. p[optional:<choice>] - Print top 10 results from each website for the given query
            <choice> : [{default : 1}, {0 : Print formatted result}, {1 : Pretty print results}]
        8. s - Enter a new query to search for over all avilable torrent websites
        9. r - Repeat last search (with same query)
        ------------------------'''
    elif arg == 1:
        print '''
        Enter 'q' to exit and 'h' to see all available commands.
        '''
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
def execute(self, context):
        webbrowser.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8TB6CNT9G8LEN")
        return {"FINISHED"}
项目:Sublime-minihtml-Preview    作者:ehuss    | 项目源码 | 文件源码
def _on_navigate(href):
    print('Navigate to: %s' % (href,))
    webbrowser.open(href)
项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def show_license(self, *args):
        def show_license(progress, on_language):
            text_license = open("LICENSE/GNU_LICENSE_{}.rst".format(
                core.dict_language[on_language])).read()

            message = KDialog(underline_color="a6b4bcff",
                              base_font_size=self.window_text_size,
                              background_image=core.theme_decorator_window)
            message.show(title="GNU_LICENSE:", text=text_license, rst=True,
                         size_rst=(.9, .7))
            progress.body.dismiss()

        if len(args) > 1:  # ??????? ?????? ? ??????
            click_link = args[1]
            webbrowser.open(click_link)
            return
        else:
            on_language = args[0]  # ?????? '?? ???????/?? ??????????'

        progress = self.create_window(text=core.string_lang_wait)
        Clock.schedule_once(lambda *args: show_license(progress, on_language),2)
项目:goodreads-api-client-python    作者:mdzhang    | 项目源码 | 文件源码
def authorize(self):
        if self._session is not None:
            return

        self._request_token, self._request_token_secret = \
            self.gr.get_request_token(header_auth=True)

        authorize_url = self._gr.get_authorize_url(self._request_token)
        webbrowser.open(authorize_url)
项目:goodreads-api-client-python    作者:mdzhang    | 项目源码 | 文件源码
def _write_credentials(self):
        blob = {
            'developer_key': self._developer_key,
            'developer_secret': self._developer_secret,
            'access_token': self.session.access_token,
            'access_token_secret': self.session.access_token_secret,
        }

        with open(credentials_file_path, 'w+') as creds_file:
            json.dump(blob, creds_file, sort_keys=True, indent=4)
项目:goodreads-api-client-python    作者:mdzhang    | 项目源码 | 文件源码
def read_credentials():
        if not os.path.exists(credentials_file_path):
            return None

        with open(credentials_file_path, 'r') as creds_file:
            return json.loads(creds_file.read())
项目:pylongecity    作者:cyrbon    | 项目源码 | 文件源码
def write_and_open_in_browser(html: str, filepath: Optional[str]):
    ''' Writes html to filepath and opens it. '''
    file = NamedTemporaryFile('w', encoding='utf-8', delete=False) if filepath is None else open(filepath, 'w', encoding='utf-8')
    file.write(html)
    file.close()
    webbrowser.open(file.name)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def tempfilepager(text, cmd):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    file = open(filename, 'w')
    file.write(text)
    file.close()
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def writedoc(thing, forceload=0):
    """Write HTML documentation to a file in the current directory."""
    try:
        object, name = resolve(thing, forceload)
        page = html.page(describe(object), html.document(object, name))
        file = open(name + '.html', 'w')
        file.write(page)
        file.close()
        print 'wrote', name + '.html'
    except (ImportError, ErrorDuringImport), value:
        print value