當前位置: 首頁>>代碼示例>>Python>>正文


Python io.BufferedReader類代碼示例

本文整理匯總了Python中java.io.BufferedReader的典型用法代碼示例。如果您正苦於以下問題:Python BufferedReader類的具體用法?Python BufferedReader怎麽用?Python BufferedReader使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了BufferedReader類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get

def get(targetURL, params, username=None):

    paramStr = ""
    for aKey in params.keys():
        paramStr+=aKey+"="+URLEncoder.encode(params[aKey], "UTF-8")+"&"
    paramStr=paramStr[:-1]
    url = URL(targetURL+"?"+paramStr)
    print url
    connection = url.openConnection()

    if username!=None:    
        userpass = username
        basicAuth = "Basic " + base64.b64encode(userpass);
        #print basicAuth
        connection.setRequestProperty ("Authorization", basicAuth);
    
    connection.setRequestMethod("GET")    
    connection.setRequestProperty("Content-Language", "en-GB")
    connection.setUseCaches(0)
    connection.setDoOutput(2)
    
    inStream= connection.getInputStream()
    rd= BufferedReader(InputStreamReader(inStream))
    response = ""
    line = rd.readLine()
    while line != None:
        response +=line+"\r"
        line = rd.readLine()
    rd.close()
    return response
開發者ID:revolutionarysystems,項目名稱:common-test,代碼行數:30,代碼來源:HttpCall.py

示例2: readWebPage

def readWebPage( webpageURL ):
    webpageURL = webpageURL.strip()
    log(VERBOSE_, "readWebpage webpageURL=" + webpageURL)
    url = URL(webpageURL)
    conn = url.openConnection()
    conn.setConnectTimeout(30000)
    conn.setReadTimeout(10000)
    conn.connect()
    responseCode = conn.getResponseCode()
    cookie = conn.getHeaderField("Set-Cookie")
    cookiePath = None
    pathDiscr = " Path="
    if cookie and cookie.find(pathDiscr) > 0:
        cookiePath = cookie[cookie.index(pathDiscr) + len(pathDiscr):]
    respLines = []
    if responseCode >= 400:
        log(ERROR_, "HTTP ERROR " + `responseCode` + ": " + `conn.getResponseMessage()`)
    else:
        log(VERBOSE_, "WebPageResponse status=" + `responseCode` + " reason=" + `conn.getResponseMessage()`)
        #log(DEBUG_,"WebPageResponse resp="+`resp` )
        reader = BufferedReader(InputStreamReader(conn.getInputStream()))
        inputLine = reader.readLine()
        while inputLine is not None:
            respLines.append(inputLine)
            inputLine = reader.readLine()

        reader.close()
    return respLines, cookiePath
開發者ID:ammula88,項目名稱:WebsphereConfigLib,代碼行數:28,代碼來源:application.py

示例3: getPayloadContent

    def getPayloadContent(self, payload):
        if payload is None:
            return ""

        try:
            sb = StringBuilder()
            reader = BufferedReader(InputStreamReader(payload.open(), "UTF-8"))
            line = reader.readLine()
            p = re.compile('\s*<\?xml.*\?>\s*')
            firstLine = True
            while line is not None:
                if firstLine:
                    if p.match(line) is not None:
                        self.log.debug("Ignoring xml declaration")
                        line = reader.readLine()
                    else:
                        sb.append(line).append("\n")
                        line = reader.readLine()
                    firstLine = False
                else:
                    sb.append(line).append("\n")
                    line = reader.readLine()
            payload.close()

            if sb:
                return sb
            return ""

        except Exception, e:
            return ""
開發者ID:the-fascinator,項目名稱:fascinator-portal,代碼行數:30,代碼來源:oai.py

示例4: readAsServer_0

 def readAsServer_0(cls, socket):
     """ generated source for method readAsServer_0 """
     br = BufferedReader(InputStreamReader(socket.getInputStream()))
     #  The first line of the HTTP request is the request line.
     requestLine = br.readLine()
     if requestLine == None:
         raise IOException("The HTTP request was empty.")
     message = str()
     if requestLine.toUpperCase().startsWith("GET "):
         message = requestLine.substring(5, requestLine.lastIndexOf(' '))
         message = URLDecoder.decode(message, "UTF-8")
         message = message.replace(str(13), ' ')
     elif requestLine.toUpperCase().startsWith("POST "):
         message = readContentFromPOST(br)
     elif requestLine.toUpperCase().startsWith("OPTIONS "):
         #  Web browsers can send an OPTIONS request in advance of sending
         #  real XHR requests, to discover whether they should have permission
         #  to send those XHR requests. We want to handle this at the network
         #  layer rather than sending it up to the actual player, so we write
         #  a blank response (which will include the headers that the browser
         #  is interested in) and throw an exception so the player ignores the
         #  rest of this request.
         HttpWriter.writeAsServer(socket, "")
         raise IOException("Drop this message at the network layer.")
     else:
         HttpWriter.writeAsServer(socket, "")
         raise IOException("Unexpected request type: " + requestLine)
     return message
開發者ID:hobson,項目名稱:ggpy,代碼行數:28,代碼來源:HttpReader.py

示例5: open

    def open(self, url_or_req):
        try:
            if isinstance(url_or_req, Request):
                connection = URL(url_or_req.get_full_url()).openConnection()
                for header in self.addheaders:
                    connection.setRequestProperty(header[0], header[1])
                for key, value in url_or_req.header_items():
                    connection.setRequestProperty(key, value)
                
                connection.setRequestMethod(url_or_req.get_method())
                
                if url_or_req.get_data() != None:
                    connection.setDoOutput(True)
                    outstream = connection.getOutputStream()
                    outstream.write(url_or_req.get_data())
            else:
                connection = URL(url_or_req).openConnection()
                for header in self.addheaders:
                    connection.setRequestProperty(header[0], header[1])

            instream = connection.getInputStream()
            doc = ""
            reader = BufferedReader(InputStreamReader(instream))
            line = reader.readLine()
            while line:
                doc += line
                line = reader.readLine()
            return Response(doc)
        except:
            traceback.print_exc()
            raise
開發者ID:rossrowe,項目名稱:sc,代碼行數:31,代碼來源:java_urllib2.py

示例6: _reader

 def _reader(self):
     stream = getResourceAsStream(self._path)
     reader = BufferedReader(InputStreamReader(stream, 'UTF-8'))
     try:
         yield reader
     finally:
         reader.close()
開發者ID:HelioGuilherme66,項目名稱:RIDE,代碼行數:7,代碼來源:jartemplate.py

示例7: _excmd

    def _excmd(self, sshcmd):
        """
        return (connected_ok, response_array)
        """
        connected_ok = True
        resp = []
        try:
            conn = Connection(self.hostname)
            conn.connect()
            self.logger.info("ssh connection created.")
            isAuthenticated = conn.authenticateWithPassword(self.user, self.password)
            if not isAuthenticated:
                connected_ok = False
                self.logger.error("ssh failed to authenticatd.")
            else:
                self.logger.info("ssh authenticated.")
                sess = conn.openSession()

                self.logger.info("ssh session created.")
                sess.execCommand(sshcmd)
                self.logger.info("ssh command issued. cmd is %s" % sshcmd)

                stdout = StreamGobbler(sess.getStdout())
                br = BufferedReader(InputStreamReader(stdout))
                while True:
                    line = br.readLine()
                    if line is None:
                        break
                    else:
                        resp.append(line)
                self.logger.warning("ssh command output: " % resp)
        except IOException, ex:
            connected_ok = False
            # print "oops..error,", ex
            self.logger.error("ssh exception: %s" % ex)
開發者ID:harryliu,項目名稱:edwin,代碼行數:35,代碼來源:__init__.py

示例8: actionPerformed

	def actionPerformed(self,actionEvent):
		accl = self.linac_setup_controller.linac_wizard_document.getAccl()
		cav_name_node_dict = self.linac_setup_controller.getCavNameNodeDict(accl)
		fc = JFileChooser(constants_lib.const_path_dict["LINAC_WIZARD_FILES_DIR_PATH"])
		fc.setDialogTitle("Read Cavities Amp. and Phases from external file ...")
		fc.setApproveButtonText("Open")
		returnVal = fc.showOpenDialog(self.linac_setup_controller.linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_in = fc.getSelectedFile()
			file_name = fl_in.getName()
			buff_in = BufferedReader(InputStreamReader(FileInputStream(fl_in)))
			line = buff_in.readLine()
			while( line != null):
				#print "debug line=",line				
				res_arr = line.split()
				if(len(res_arr) == 3):
					cav_name = res_arr[0]
					amp = float(res_arr[1])
					phase = float(res_arr[2])
					if(cav_name_node_dict.has_key(cav_name)):
						#print "debug cav=",cav_name," amp=",amp," phase",phase						
						cav = cav_name_node_dict[cav_name]
						cav.setDfltCavAmp(amp)
						cav.setDfltCavPhase(phase)
				line = buff_in.readLine()
開發者ID:kritha,項目名稱:MyOpenXal,代碼行數:25,代碼來源:linac_setup_cntrl_lib.py

示例9: _read_from_stream

 def _read_from_stream(self, stream):
     reader = BufferedReader(InputStreamReader(StreamGobbler(stream)))
     result = ""
     line = reader.readLine()
     while line is not None:
         result += line + "\n"
         line = reader.readLine()
     return result
開發者ID:ktan2020,項目名稱:legacy-automation,代碼行數:8,代碼來源:javaclient.py

示例10: run

 def run(self):
     while (rhost.keepAlive == 1):
         lang.Thread.sleep(interval)
         sess = rhost.connection.openSession()
         sess.execCommand(command) # execute command
         inputreader = BufferedReader(InputStreamReader(sess.getStdout()))
         inputreader.readLine()
         sess.close()
開發者ID:gidiko,項目名稱:gridapp,代碼行數:8,代碼來源:ssh.py

示例11: read_jar_stream

 def read_jar_stream(self, template_path):
     reader = BufferedReader(InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(template_path)))
     line = reader.readLine()
     sb = StringBuilder()
     while line is not None:
         sb.append(line).append("\n")
         line = reader.readLine()
     return sb.toString()
開發者ID:rotoudjimaye,項目名稱:django-jy,代碼行數:8,代碼來源:jar.py

示例12: readFile

 def readFile(cls, rootFile):
     """ generated source for method readFile """
     #  Show contents of the file.
     fr = FileReader(rootFile)
     br = BufferedReader(fr)
     try:
         while (line = br.readLine()) != None:
             response += line + "\n"
         return response
開發者ID:hobson,項目名稱:ggpy,代碼行數:9,代碼來源:LocalGameRepository.py

示例13: _read_from_stream

 def _read_from_stream(self, stream):
     reader = BufferedReader(InputStreamReader(StreamGobbler(stream),
                                               self._encoding))
     result = ''
     line = reader.readLine()
     while line is not None:
         result += line + '\n'
         line = reader.readLine()
     return result
開發者ID:DeepeshKaushal,項目名稱:SSHLibrary,代碼行數:9,代碼來源:javaclient.py

示例14: run

 def run(self):
     reader = BufferedReader(InputStreamReader(self.getStream()))
     try:
         line = reader.readLine()
         while line:
             self.output += line
             line = reader.readLine()
     finally:
         reader.close()
開發者ID:Alex-CS,項目名稱:sonify,代碼行數:9,代碼來源:test_bat_jy.py

示例15: __metadata

    def __metadata(self):
        ISOCode = self.params.getProperty("ISOcode")
        print "*** Processing: ", ISOCode
        #Index the country metadata
        metadataPayload = self.object.getPayload("%s.json" % ISOCode)
        json = JsonConfigHelper(metadataPayload.open())
        allMeta = json.getMap(".")
        self.utils.add(self.index, "recordType", "country")
        for key in allMeta.keySet():
            self.utils.add(self.index, key, allMeta.get(key));
        metadataPayload.close()

        #Index the country detail
        geoNamePayload = self.object.getPayload("%s.txt" % ISOCode)
        countryName = self.params.getProperty("countryName")
    
        countryAreaStream = geoNamePayload.open()
        reader = BufferedReader(InputStreamReader(countryAreaStream, "UTF-8"));
        line = reader.readLine()
        
        headerList = ["geonameid", "name", "asciiname", "alternatenames", "latitude", "longitude", \
                      "feature class", "feature code", "country code", "cc2", "admin1 code", "admin2 code", \
                      "admin3 code", "admin4 code", "population", "elevation", "gtopo30", "timezone", "modification date"]
        
        while (line != None):
            arraySplit = line.split("\t")
            geonamesId = arraySplit[0]
            oid = DigestUtils.md5Hex("http://geonames.org/" + geonamesId)

            if oid == self.oid:
                extraIndex = self.index
            else:
                extraIndex = HashMap()
                self.utils.add(extraIndex, "recordType", "area")
                self.utils.add(extraIndex, "item_type", self.itemType)
                self.utils.add(extraIndex, "dc_identifier", oid)
                self.utils.add(extraIndex, "id", oid)
                self.utils.add(extraIndex, "storage_id", self.oid)   #Use parent object
                self.utils.add(extraIndex, "last_modified", time.strftime("%Y-%m-%dT%H:%M:%SZ"))
                self.utils.add(extraIndex, "display_type", "geonames")
                self.utils.add(extraIndex, "countryName", countryName)
                self.utils.add(extraIndex, "repository_name", self.params["repository.name"])
                self.utils.add(extraIndex, "repository_type", self.params["repository.type"])
                self.utils.add(extraIndex, "security_filter", "guest")
            self.utils.add(extraIndex, "dc_title", arraySplit[1])
            # The rest of the metadata
            count = 0
            for array in arraySplit:
                if headerList[count] !="alternatenames" and array:
                    self.utils.add(extraIndex, headerList[count], array)
                count +=1
                
            self.indexer.sendIndexToBuffer(oid, extraIndex)
            line = reader.readLine()
        geoNamePayload.close()
        
開發者ID:kiranba,項目名稱:the-fascinator,代碼行數:55,代碼來源:geonames.py


注:本文中的java.io.BufferedReader類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。