本文整理汇总了Python中PyQt5.QtCore.QTextStream.readLine方法的典型用法代码示例。如果您正苦于以下问题:Python QTextStream.readLine方法的具体用法?Python QTextStream.readLine怎么用?Python QTextStream.readLine使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QTextStream
的用法示例。
在下文中一共展示了QTextStream.readLine方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: go_to_definition
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def go_to_definition(self):
self.dirty = True
self.results = []
locations = self.get_locations()
if self._isVariable:
preResults = [
[file_manager.get_basename(x.path), x.path, x.lineno, '']
for x in locations
if (x.type == FILTERS['attribs']) and (x.name == self._search)]
else:
preResults = [
[file_manager.get_basename(x.path), x.path, x.lineno, '']
for x in locations
if ((x.type == FILTERS['functions']) or
(x.type == FILTERS['classes'])) and
(x.name.startswith(self._search))]
for data in preResults:
file_object = QFile(data[1])
if not file_object.open(QFile.ReadOnly):
return
stream = QTextStream(file_object)
line_index = 0
line = stream.readLine()
while not self._cancel and not stream.atEnd():
if line_index == data[2]:
data[3] = line
self.results.append(data)
break
#take the next line!
line = stream.readLine()
line_index += 1
示例2: openFile
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def openFile(self, path=None):
if not path:
path, _ = QFileDialog.getOpenFileName(self, "Choose a data file",
'', '*.cht')
if path:
f = QFile(path)
if f.open(QFile.ReadOnly | QFile.Text):
stream = QTextStream(f)
self.model.removeRows(0, self.model.rowCount(QModelIndex()),
QModelIndex())
row = 0
line = stream.readLine()
while line:
self.model.insertRows(row, 1, QModelIndex())
pieces = line.split(',')
self.model.setData(self.model.index(row, 0, QModelIndex()),
pieces[0])
self.model.setData(self.model.index(row, 1, QModelIndex()),
float(pieces[1]))
self.model.setData(self.model.index(row, 0, QModelIndex()),
QColor(pieces[2]), Qt.DecorationRole)
row += 1
line = stream.readLine()
f.close()
self.statusBar().showMessage("Loaded %s" % path, 2000)
示例3: loadDescription
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def loadDescription(self, startPara, nrPara):
readme = QFile(self.readmePath)
if not readme.open(QFile.ReadOnly):
Colors.debug("- MenuContentItem.loadDescription: Could not load:", self.readmePath)
return ""
in_str = QTextStream(readme)
# Skip a certain number of paragraphs.
while startPara:
if not in_str.readLine():
startPara -= 1
# Read in the number of wanted paragraphs.
result = ""
line = in_str.readLine()
while True:
result += line + " "
line = in_str.readLine()
if not line:
nrPara -= 1
line = "<br><br>" + in_str.readLine()
if nrPara == 0 or in_str.atEnd():
break
return Colors.contentColor + result
示例4: _grep_file
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def _grep_file(self, file_path, file_name):
"""Search for each line inside the file."""
if not self.by_phrase:
with open(file_path, 'r') as f:
content = f.read()
words = [word for word in
self.search_pattern.pattern().split('|')]
words.insert(0, True)
def check_whole_words(result, word):
return result and content.find(word) != -1
if not reduce(check_whole_words, words):
return
file_object = QFile(file_path)
if not file_object.open(QFile.ReadOnly):
return
stream = QTextStream(file_object)
lines = []
line_index = 0
line = stream.readLine()
while not self._cancel and not (stream.atEnd() and not line):
column = self.search_pattern.indexIn(line)
if column != -1:
lines.append((line_index, line))
#take the next line!
line = stream.readLine()
line_index += 1
#emit a signal!
relative_file_name = file_manager.convert_to_relative(
self.root_dir, file_path)
self.found_pattern.emit((relative_file_name, lines))
示例5: findFiles
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def findFiles(self, files, text):
progressDialog = QProgressDialog(self)
progressDialog.setCancelButtonText("&Cancel")
progressDialog.setRange(0, files.count())
progressDialog.setWindowTitle("Find Files")
foundFiles = []
for i in range(files.count()):
progressDialog.setValue(i)
progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
QApplication.processEvents()
if progressDialog.wasCanceled():
break
inFile = QFile(self.currentDir.absoluteFilePath(files[i]))
if inFile.open(QIODevice.ReadOnly):
stream = QTextStream(inFile)
while not stream.atEnd():
if progressDialog.wasCanceled():
break
line = stream.readLine()
if text in line:
foundFiles.append(files[i])
break
progressDialog.close()
return foundFiles
示例6: _grep_file
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def _grep_file(self, file_path, file_name):
"""Search for each line inside the file"""
file_obj = QFile(file_path)
if not file_obj.open(QFile.ReadOnly):
return
stream = QTextStream(file_obj)
lines = []
append = lines.append
line_index = 0
line = stream.readLine()
while not self._cancel and not stream.atEnd():
column = self.search_pattern.indexIn(line)
if column != -1:
append((line_index, line))
# Take the next line
line = stream.readLine()
line_index += 1
p = os.path.join(self.root_dir, file_path)
self.resultAvailable.emit((p, lines))
示例7: readExtension
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def readExtension(self, fileName):
extFile = QFile(fileName)
extFile.open(QIODevice.ReadOnly)
extension = {}
stream = QTextStream(extFile)
while not stream.atEnd():
line = stream.readLine()
if '=' in line:
index = line.index('=')
extension[line[:index].rstrip()] = line[index+1:].lstrip()
extFile.close()
return extension
示例8: loadFile
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def loadFile(self, filePath):
ret = True
absPath = QFileInfo(filePath).path()
rulesFile = QFile(filePath)
if (not rulesFile.exists()):
self.mError += self.tr("No rules file found at:\n%s\n"%filePath)
return False
if (not rulesFile.open(QIODevice.ReadOnly | QIODevice.Text)):
self.mError += self.tr("Error opening rules file:\n%s\n"%filePath)
return False
i = QTextStream(rulesFile)
line = ' '
while line != '':
line = i.readLine()
rulePath = line.strip()
if (rulePath=='' or rulePath.startswith('#') or rulePath.startswith("//")):
continue
if (QFileInfo(rulePath).isRelative()):
rulePath = absPath + '/' + rulePath
if (not QFileInfo(rulePath).exists()):
self.mError += self.tr("File not found:\n%s"%rulePath) + '\n'
ret = False
continue
if (rulePath.lower().endswith(".tmx")):
tmxFormat = TmxMapFormat()
rules = tmxFormat.read(rulePath)
if (not rules):
self.mError += self.tr("Opening rules map failed:\n%s"%tmxFormat.errorString()) + '\n'
ret = False
continue
tilesetManager = TilesetManager.instance()
tilesetManager.addReferences(rules.tilesets())
autoMapper = None
autoMapper = AutoMapper(self.mMapDocument, rules, rulePath)
self.mWarning += autoMapper.warningString()
error = autoMapper.errorString()
if error != '':
self.mAutoMappers.append(autoMapper)
else:
self.mError += error
del autoMapper
if (rulePath.lower().endswith(".txt")):
if (not self.loadFile(rulePath)):
ret = False
return ret
示例9: QtSingleApplication
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
#.........这里部分代码省略.........
messageReceived = pyqtSignal(unicode)
def __init__(self, win_id, *argv):
logfunc = logging.info
logfunc(sys._getframe().f_code.co_name + '()')
QApplication.__init__(self, *argv)
self._id = win_id
self._activation_window = None
self._activate_on_message = False
# Is there another instance running?
self._outSocket = QLocalSocket()
self._outSocket.connectToServer(self._id)
self._isRunning = self._outSocket.waitForConnected()
self._outStream = None
self._inSocket = None
self._inStream = None
self._server = None
if self._isRunning:
# Yes, there is.
self._outStream = QTextStream(self._outSocket)
self._outStream.setCodec('UTF-8')
else:
# No, there isn't, at least not properly.
# Cleanup any past, crashed server.
error = self._outSocket.error()
logfunc(LOGVARSTR % ('self._outSocket.error()', error))
if error == QLocalSocket.ConnectionRefusedError:
logfunc('received QLocalSocket.ConnectionRefusedError; ' + \
'removing server.')
self.close()
QLocalServer.removeServer(self._id)
self._outSocket = None
self._server = QLocalServer()
self._server.listen(self._id)
self._server.newConnection.connect(self._on_new_connection)
logfunc(sys._getframe().f_code.co_name + '(): returning')
def close(self):
logfunc = logging.info
logfunc(sys._getframe().f_code.co_name + '()')
if self._inSocket:
self._inSocket.disconnectFromServer()
if self._outSocket:
self._outSocket.disconnectFromServer()
if self._server:
self._server.close()
logfunc(sys._getframe().f_code.co_name + '(): returning')
def is_running(self):
return self._isRunning
def get_id(self):
return self._id
def activation_window(self):
return self._activation_window
def set_activation_window(self, activation_window, activate_on_message=True):
self._activation_window = activation_window
self._activate_on_message = activate_on_message
def activate_window(self):
if not self._activation_window:
return
self._activation_window.setWindowState(
self._activation_window.windowState() & ~Qt.WindowMinimized)
self._activation_window.raise_()
def send_message(self, msg):
if not self._outStream:
return False
self._outStream << msg << '\n'
self._outStream.flush()
return self._outSocket.waitForBytesWritten()
def _on_new_connection(self):
if self._inSocket:
self._inSocket.readyRead.disconnect(self._on_ready_read)
self._inSocket = self._server.nextPendingConnection()
if not self._inSocket:
return
self._inStream = QTextStream(self._inSocket)
self._inStream.setCodec('UTF-8')
self._inSocket.readyRead.connect(self._on_ready_read)
if self._activate_on_message:
self.activate_window()
def _on_ready_read(self):
while True:
msg = self._inStream.readLine()
if not msg:
break
self.messageReceived.emit(msg)
示例10: __loadRules
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def __loadRules(self):
"""
Private method to load the rules of the subscription.
"""
fileName = self.rulesFileName()
f = QFile(fileName)
if f.exists():
if not f.open(QIODevice.ReadOnly):
E5MessageBox.warning(
None,
self.tr("Load subscription rules"),
self.tr(
"""Unable to open adblock file '{0}' for reading.""")
.format(fileName))
else:
textStream = QTextStream(f)
header = textStream.readLine(1024)
if not header.startswith("[Adblock"):
E5MessageBox.warning(
None,
self.tr("Load subscription rules"),
self.tr("""AdBlock file '{0}' does not start"""
""" with [Adblock.""")
.format(fileName))
f.close()
f.remove()
self.__lastUpdate = QDateTime()
else:
from .AdBlockRule import AdBlockRule
self.__updatePeriod = 0
self.__remoteModified = QDateTime()
self.__rules = []
self.__rules.append(AdBlockRule(header, self))
while not textStream.atEnd():
line = textStream.readLine()
self.__rules.append(AdBlockRule(line, self))
expires = self.__expiresRe.search(line)
if expires:
period, kind = expires.groups()
if kind:
# hours
self.__updatePeriod = int(period)
else:
# days
self.__updatePeriod = int(period) * 24
remoteModified = self.__remoteModifiedRe.search(line)
if remoteModified:
day, month, year, time, hour, minute = \
remoteModified.groups()
self.__remoteModified.setDate(
QDate(int(year),
self.__monthNameToNumber[month],
int(day))
)
if time:
self.__remoteModified.setTime(
QTime(int(hour), int(minute)))
self.__populateCache()
self.changed.emit()
elif not fileName.endswith("_custom"):
self.__lastUpdate = QDateTime()
self.checkForUpdate()
示例11: QtSingleApplication
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
class QtSingleApplication(QApplication):
messageReceived = pyqtSignal(str)
def __init__(self, id, *argv):
super(QtSingleApplication, self).__init__(*argv)
self._id = id
self._activationWindow = None
self._activateOnMessage = False
# Is there another instance running?
self._outSocket = QLocalSocket()
self._outSocket.connectToServer(self._id)
self._isRunning = self._outSocket.waitForConnected()
if self._isRunning:
# Yes, there is.
self._outStream = QTextStream(self._outSocket)
self._outStream.setCodec("UTF-8")
else:
# No, there isn't.
self._outSocket = None
self._outStream = None
self._inSocket = None
self._inStream = None
self._server = QLocalServer()
self._server.listen(self._id)
self._server.newConnection.connect(self._onNewConnection)
def isRunning(self):
return self._isRunning
def id(self):
return self._id
def activationWindow(self):
return self._activationWindow
def setActivationWindow(self, activationWindow, activateOnMessage=True):
self._activationWindow = activationWindow
self._activateOnMessage = activateOnMessage
def activateWindow(self):
if not self._activationWindow:
return
self._activationWindow.show()
self._activationWindow.setWindowState(self._activationWindow.windowState() & ~Qt.WindowMinimized)
self._activationWindow.raise_()
self._activationWindow.activateWindow()
def sendMessage(self, msg):
if not self._outStream:
return False
self._outStream << msg << "\n"
self._outStream.flush()
return self._outSocket.waitForBytesWritten()
def _onNewConnection(self):
if self._inSocket:
self._inSocket.readyRead.disconnect(self._onReadyRead)
self._inSocket = self._server.nextPendingConnection()
if not self._inSocket:
return
self._inStream = QTextStream(self._inSocket)
self._inStream.setCodec("UTF-8")
self._inSocket.readyRead.connect(self._onReadyRead)
if self._activateOnMessage:
self.activateWindow()
def _onReadyRead(self):
while True:
msg = self._inStream.readLine()
if not msg:
break
self.messageReceived.emit(msg)
示例12: Eddy
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
#.........这里部分代码省略.........
self.openFile(filepath)
####################################################################################################################
# #
# EVENTS #
# #
####################################################################################################################
def event(self, event):
"""
Executed when an event is received.
:type event: T <= QEvent | QFileOpenEvent
"""
if event.type() == QEvent.FileOpen:
self.pendingOpen = [event.file()]
return True
return super().event(event)
####################################################################################################################
# #
# INTERFACE #
# #
####################################################################################################################
def activate(self):
"""
Activate the application by raising the main window.
"""
if self.mainwindow:
self.mainwindow.setWindowState((self.mainwindow.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive)
self.mainwindow.activateWindow()
self.mainwindow.raise_()
def openFile(self, filepath):
"""
Open the given file in the activation window.
:type filepath: str
:rtype: bool
"""
if self.mainwindow:
if not isEmpty(filepath) and os.path.isfile(filepath) and filepath.endswith(Filetype.Graphol.extension):
self.mainwindow.openFile(filepath)
return True
return False
def sendMessage(self, message):
"""
Send a message to the other alive Eddy's process.
:type message: str
:rtype: bool
"""
if self.outStream:
self.outStream = self.outStream << message << '\n'
self.outStream.flush()
return self.outSocket.waitForBytesWritten()
return False
####################################################################################################################
# #
# SLOTS #
# #
####################################################################################################################
@pyqtSlot()
def newConnection(self):
"""
Executed whenever a message is received.
"""
if self.inSocket:
# Disconnect previously connected signal slot.
disconnect(self.inSocket.readyRead, self.readyRead)
# Create a new socket.
self.inSocket = self.server.nextPendingConnection()
if self.inSocket:
self.inStream = QTextStream(self.inSocket)
self.inStream.setCodec('UTF-8')
connect(self.inSocket.readyRead, self.readyRead)
self.activate()
@pyqtSlot()
def readyRead(self):
"""
Executed whenever we need to read a message.
"""
while True:
message = self.inStream.readLine()
if isEmpty(message):
break
self.messageReceived.emit(message)
@pyqtSlot(str)
def readMessage(self, message):
"""
Read a received message.
:type message: str
"""
for filepath in message.split(' '):
self.openFile(filepath)
示例13: read
# 需要导入模块: from PyQt5.QtCore import QTextStream [as 别名]
# 或者: from PyQt5.QtCore.QTextStream import readLine [as 别名]
def read(self, fileName):
file = QFile(fileName)
if (not file.open (QIODevice.ReadOnly)):
self.mError = self.tr("Could not open file for reading.")
return None
# default to values of the original flare alpha game.
map = Map(Map.Orientation.Isometric, 256, 256, 64, 32)
stream = QTextStream(file)
line = QString()
sectionName = QString()
newsection = False
path = QFileInfo(file).absolutePath()
base = 10
gidMapper = GidMapper()
gid = 1
tilelayer = None
objectgroup = None
mapobject = None
tilesetsSectionFound = False
headerSectionFound = False
tilelayerSectionFound = False # tile layer or objects
while (not stream.atEnd()):
line = stream.readLine()
if line == '':
continue
startsWith = line[0]
if (startsWith == '['):
sectionName = line[1:line.index(']')]
newsection = True
continue
if (sectionName == "header"):
headerSectionFound = True
#get map properties
epos = line.index('=')
if (epos != -1):
key = line[:epos].strip()
value = line[epos + 1:].strip()
if (key == "width"):
map.setWidth(Int(value))
elif (key == "height"):
map.setHeight(Int(value))
elif (key == "tilewidth"):
map.setTileWidth(Int(value))
elif (key == "tileheight"):
map.setTileHeight(Int(value))
elif (key == "orientation"):
map.setOrientation(orientationFromString(value))
else:
map.setProperty(key, value)
elif (sectionName == "tilesets"):
tilesetsSectionFound = True
epos = line.index('=')
key = line[:epos].strip()
value = line[epos + 1:].strip()
if (key == "tileset"):
_list = value.split(',')
absoluteSource = _list[0]
if (QDir.isRelativePath(absoluteSource)):
absoluteSource = path + '/' + absoluteSource
tilesetwidth = 0
tilesetheight = 0
if len(_list) > 2:
tilesetwidth = Int(_list[1])
tilesetheight = Int(_list[2])
tileset = Tileset.create(QFileInfo(absoluteSource).fileName(), tilesetwidth, tilesetheight)
ok = tileset.loadFromImage(absoluteSource)
if not ok:
self.mError = self.tr("Error loading tileset %s, which expands to %s. Path not found!"%(_list[0], absoluteSource))
return None
else :
if len(_list) > 4:
tileset.setTileOffset(QPoint(Int(_list[3]),Int(_list[4])))
gidMapper.insert(gid, tileset)
if len(_list) > 5:
gid += Int(_list[5])
else :
gid += tileset.tileCount()
map.addTileset(tileset)
elif (sectionName == "layer"):
if (not tilesetsSectionFound):
self.mError = self.tr("No tilesets section found before layer section.")
return None
tilelayerSectionFound = True
epos = line.index('=')
if (epos != -1):
key = line[:epos].strip()
value = line[epos + 1:].strip()
if (key == "type"):
tilelayer = TileLayer(value, 0, 0, map.width(),map.height())
map.addLayer(tilelayer)
elif (key == "format"):
if (value == "dec"):
base = 10
#.........这里部分代码省略.........