def save(self, content, path=None): """ Write a temprorary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File #FIXME: Where to locate addExtension, does not fit here """ new_path = False if path: self.attach_to_path(path) new_path = True save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = "%s.nsp" % save_path # If we have a file system watcher, remove the file path # from its watch list until we are done making changes. if self.__watcher: self.__watcher.removePath(save_path) flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() #SIGNAL: Will save (temp, definitive) to warn folder to do something self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path, save_path) self.__mtime = os.path.getmtime(swap_save_path) shutil.move(swap_save_path, save_path) self.reset_state() # If we have a file system watcher, add the saved path back # to its watch list, otherwise create a watcher and start # watching if self.__watcher: if new_path: self.__watcher.removePath(self.__watcher.files()[0]) self.__watcher.addPath(self._file_path) else: self.__watcher.addPath(save_path) else: self.start_watching() return self
def WriteUserInfoFile(self): if QFile.exists(self.m_strUserInfoFullName): fl = QFile.remove(self.m_strUserInfoFullName) f = open(self.m_strUserInfoFullName, 'w') f.flush() f.close() else: f = open(self.m_strUserInfoFullName, 'w') # f = open("D:/xml/phxasar.txt") f.flush() f.close() file0 = QFile(self.m_strUserInfoFullName) file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("UserList")) dataStream.writeQString(QString(self.m_strUserInfoFullName)) dataStream.writeQString(QString(self.m_Key)) dataStream.writeQString(QString(self.m_IV)) dataStream.writeInt(len(self.ListUserInfo)) for userInfo in self.ListUserInfo: userInfo.writeData(dataStream) file0.flush() file0.close() return True
def escribir_archivo(nombre_de_archivo, contenido): """ Se escribe en el archivo, si el nombre no tiene extensión se agrega .c """ extension = (os.path.splitext(nombre_de_archivo)[-1])[1:] if not extension: nombre_de_archivo += '.c' try: f = QFile(nombre_de_archivo) if not f.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning("Guardar", "No se escribio en %s: %s" % ( nombre_de_archivo, f.errorString())) return False flujo = QTextStream(f) encode_flujo = flujo.codec().fromUnicode(contenido) f.write(encode_flujo) f.flush() f.close() except: pass return os.path.abspath(nombre_de_archivo)
def save(self, content, path=None): """ Write a temprorary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File #FIXME: Where to locate addExtension, does not fit here """ if path and self._file_path: created_file = NFile(path).save(content) self.emit(SIGNAL("savedAsNewFile(PyQt_PyObject, QString, QString)"), created_file, self._file_path, path) return created_file elif path and not self._file_path: self.attach_to_path(path) save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = u"%s.nsp" % save_path flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() #SIGNAL: Will save (temp, definitive) to warn folder to do something self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path, save_path) shutil.move(swap_save_path, save_path) self.reset_state() return self
def method_0(self, iwin32Window_0): if QFile.exists(FatoList.fileName): fl = QFile.remove(FatoList.fileName) f = open(FatoList.fileName, 'w') f.flush() f.close() else: f = open(FatoList.fileName, 'w') # f = open("D:/xml/phxasar.txt") f.flush() f.close() file0 = QFile(FatoList.fileName) file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("PHXHSAF")) dataStream.writeInt(1) dataStream.writeInt(len(self)) for fato in self: fato.method_6(dataStream) file0.flush() file0.close()
class ReceiveController(QObject): streamCreated = pyqtSignal(int) contentReceived = pyqtSignal('QByteArray') nextPacketRequests = pyqtSignal('QString', list, list) def __init__(self): super(ReceiveController, self).__init__() self.__file = None self.__pid2ready = dict() self.__current_sid = str() def recreate(self, stream_id, peer_id, size): peer_id = str(peer_id) stream_id = str(stream_id) if self.__current_sid == stream_id: self.add_peer(peer_id) return else: self.__current_sid = stream_id self.__last_packet = 0 self.__last_peer = 0 self.__inbox = list() if self.__file is not None: if self.__file.isOpen(): self.__file.close() self.__file.remove() filename = 'files/%s.mp3' % ''.join([chr(randint(ord('a'), ord('z'))) for _ in xrange(10)]) self.__file = QFile(filename) self.__file.open(QIODevice.ReadWrite) self.__pid2ready = {peer_id: True} self.__fisrt = True self.__data_consistent_to = 0 self.__was_null = False self.__offset = 0 pids, packet_nums = self.get_packet_requests() self.nextPacketRequests.emit(self.__current_sid, pids, packet_nums) self.streamCreated.emit(size) def get_peers(self): return self.__pid2ready.keys() def get_packet_requests(self): if len(self.__pid2ready.keys()) > 0: ready_pids = filter(lambda key: self.__pid2ready[key], self.__pid2ready.keys()) for pid in ready_pids: self.__pid2ready[pid] = False last_pack = self.__last_packet self.__last_packet += 1 return (ready_pids, range(last_pack, last_pack + len(ready_pids))) else: return None def add_peer(self, peer_id): self.__peers[str(peer_id)] = True def remove_peer(self, peer_id): if peer_id in self.__pid2ready.keys(): del self.__pid2ready[peer_id] def __consistent_to(self): if not self.__was_null: return 0 for i, _ in enumerate(self.__inbox[self.__data_consistent_to:-1]): if self.__inbox[i + 1][0] - self.__inbox[i][0] != 1: self.__data_consistent_to = i return i if len(self.__inbox) > 0: self.__data_consistent_to = self.__inbox[len(self.__inbox) - 1][0] return self.__data_consistent_to def receive_packet(self, _from, peer_id, data): peer_id, data = str(peer_id), str(data) debug('ReceiveController().receive_packet(): Binary from %s has been received' % peer_id) if _from == 0: self.__was_null = True self.__pid2ready[peer_id] = True i = 0 while i < len(self.__inbox) and self.__inbox[i][0] < _from: i += 1 self.__inbox.insert(i, (_from, data)) if len(self.__inbox) > 0: self.__last_packet = self.__inbox[len(self.__inbox) - 1][0] + 1 cons_to = self.__consistent_to() if cons_to > -1: inbox = map(lambda x: x[1], self.__inbox) final_data = "".join(inbox[:cons_to]) self.contentReceived.emit(final_data) pids, nums = self.get_packet_requests() self.nextPacketRequests.emit(self.__current_sid, pids, nums) self.__file.writeData(final_data) self.__file.flush() self.__inbox = self.__inbox[cons_to:]
class Dialog(QDialog): TotalBytes = 50 * 1024 * 1024 PayloadSize = 65536 def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.settings = QSettings('settings.ini', QSettings.IniFormat) self.tcpServer = QTcpServer() self.chBox = QCheckBox("Print log to window") self.text = QPlainTextEdit() self.serverStatusLabel = QLabel("Server ready") self.lblFileName = QLabel("Choose file before start!") self.saveButton = QPushButton("&Choose file...") self.startButton = QPushButton("&Start") self.stopButton = QPushButton("S&top") self.quitButton = QPushButton("&Quit") self.file = None self.tcpServerConnection = None self._lineCounter = 0 self._lineBuf = '' buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) clearButon = QPushButton('&Clear') self.saveButton.clicked.connect(self.savedlg) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stopClicked) self.quitButton.clicked.connect(self.close) clearButon.clicked.connect(self.text.clear) self.tcpServer.newConnection.connect(self.acceptConnection) saveLayout = QHBoxLayout() saveLayout.addWidget(self.lblFileName) saveLayout.addStretch(1) saveLayout.addWidget(self.saveButton) topTextLayout = QHBoxLayout() topTextLayout.addWidget(self.chBox) topTextLayout.addStretch(1) topTextLayout.addWidget(clearButon) mainLayout = QVBoxLayout() mainLayout.addLayout(saveLayout) mainLayout.addLayout(topTextLayout) mainLayout.addWidget(self.text) mainLayout.addWidget(self.serverStatusLabel) # mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.title = "Simple Logger" self.ver = '1.0' self.setWindowIcon(QIcon('./icon.png')) self.setWindowTitle("{} {}".format(self.title, self.ver)) def start(self): if self.file is None: QMessageBox.critical(self, self.title, "Unable open log file.\nPlease, select another file.") return self.startButton.setEnabled(False) while not self.tcpServer.isListening() and not self.tcpServer.listen(port=9112): ret = QMessageBox.critical(self, self.title, "Unable to start the test: %s." % self.tcpServer.errorString(), QMessageBox.Retry | QMessageBox.Cancel) if ret == QMessageBox.Cancel: return self.serverStatusLabel.setText("Waiting connection ...") def acceptConnection(self): self.tcpServerConnection = self.tcpServer.nextPendingConnection() self.tcpServerConnection.readyRead.connect(self.updateLog) self.tcpServerConnection.error.connect(self.displayError) self.file = QFile(self.filename) if not self.file.open(QFile.Append): QMessageBox.warning(self, self.title, "Unable to write file {}:\n{}.".format(self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.serverStatusLabel.setText("Logging ...") self.tcpServer.close() def savedlg(self): self.filename = QFileDialog.getSaveFileName(self, "Log Filename", self.settings.value('directories/dir_save', QDir.currentPath()), "Text (*.log *.txt);;All (*)") if not self.filename: return self.file = QFile(self.filename) self.lblFileName.setText(self.filename) if not self.file.open(QFile.WriteOnly): QMessageBox.warning(self, self.title, "Unable to write file {}:\n{}.".format(self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.settings.setValue('directories/dir_save', QFileInfo(self.file).path()) self.file.close() def updateLog(self): if self.tcpServerConnection.bytesAvailable(): data = self.tcpServerConnection.readAll() line = "{}".format(str(data.data().decode())) if self.chBox.isChecked(): self._lineCounter += 1 self._lineBuf += line if self._lineCounter > 10: self.text.appendPlainText(self._lineBuf) self._lineCounter = 0 self._lineBuf = '' self.textStream << line self.file.flush() # self.serverStatusLabel.setText(line) def closeEvent(self, event): if self.file is not None: self.file.flush() self.file.close() def stopClicked(self): if self.tcpServerConnection is not None: self.tcpServerConnection.close() self.file.close() self.startButton.setEnabled(True) self.serverStatusLabel.setText("Logger ready") def displayError(self, socketError): if socketError == QTcpSocket.RemoteHostClosedError: return QMessageBox.information(self, "Network error", "The following error occured: %s." % self.tcpServer.errorString()) self.tcpServer.close() self.file.close() self.serverStatusLabel.setText("Logger ready") self.startButton.setEnabled(True)
class Dialog(QDialog): TotalBytes = 50 * 1024 * 1024 PayloadSize = 65536 def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.settings = QSettings('settings.ini', QSettings.IniFormat) self.tcpServer = QTcpServer() self.chBox = QCheckBox("Print log to window") self.text = QPlainTextEdit() self.serverStatusLabel = QLabel("Server ready") self.lblFileName = QLabel("Choose file before start!") self.saveButton = QPushButton("&Choose file...") self.startButton = QPushButton("&Start") self.stopButton = QPushButton("S&top") self.quitButton = QPushButton("&Quit") self.file = None self.tcpServerConnection = None self._lineCounter = 0 self._lineBuf = '' buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) clearButon = QPushButton('&Clear') self.saveButton.clicked.connect(self.savedlg) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stopClicked) self.quitButton.clicked.connect(self.close) clearButon.clicked.connect(self.text.clear) self.tcpServer.newConnection.connect(self.acceptConnection) saveLayout = QHBoxLayout() saveLayout.addWidget(self.lblFileName) saveLayout.addStretch(1) saveLayout.addWidget(self.saveButton) topTextLayout = QHBoxLayout() topTextLayout.addWidget(self.chBox) topTextLayout.addStretch(1) topTextLayout.addWidget(clearButon) mainLayout = QVBoxLayout() mainLayout.addLayout(saveLayout) mainLayout.addLayout(topTextLayout) mainLayout.addWidget(self.text) mainLayout.addWidget(self.serverStatusLabel) # mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.title = "Simple Logger" self.ver = '1.0' self.setWindowIcon(QIcon('./icon.png')) self.setWindowTitle("{} {}".format(self.title, self.ver)) def start(self): if self.file is None: QMessageBox.critical( self, self.title, "Unable open log file.\nPlease, select another file.") return self.startButton.setEnabled(False) while not self.tcpServer.isListening() and not self.tcpServer.listen( port=9112): ret = QMessageBox.critical( self, self.title, "Unable to start the test: %s." % self.tcpServer.errorString(), QMessageBox.Retry | QMessageBox.Cancel) if ret == QMessageBox.Cancel: return self.serverStatusLabel.setText("Waiting connection ...") def acceptConnection(self): self.tcpServerConnection = self.tcpServer.nextPendingConnection() self.tcpServerConnection.readyRead.connect(self.updateLog) self.tcpServerConnection.error.connect(self.displayError) self.file = QFile(self.filename) if not self.file.open(QFile.Append): QMessageBox.warning( self, self.title, "Unable to write file {}:\n{}.".format( self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.serverStatusLabel.setText("Logging ...") self.tcpServer.close() def savedlg(self): self.filename = QFileDialog.getSaveFileName( self, "Log Filename", self.settings.value('directories/dir_save', QDir.currentPath()), "Text (*.log *.txt);;All (*)") if not self.filename: return self.file = QFile(self.filename) self.lblFileName.setText(self.filename) if not self.file.open(QFile.WriteOnly): QMessageBox.warning( self, self.title, "Unable to write file {}:\n{}.".format( self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.settings.setValue('directories/dir_save', QFileInfo(self.file).path()) self.file.close() def updateLog(self): if self.tcpServerConnection.bytesAvailable(): data = self.tcpServerConnection.readAll() line = "{}".format(str(data.data().decode())) if self.chBox.isChecked(): self._lineCounter += 1 self._lineBuf += line if self._lineCounter > 10: self.text.appendPlainText(self._lineBuf) self._lineCounter = 0 self._lineBuf = '' self.textStream << line self.file.flush() # self.serverStatusLabel.setText(line) def closeEvent(self, event): if self.file is not None: self.file.flush() self.file.close() def stopClicked(self): if self.tcpServerConnection is not None: self.tcpServerConnection.close() self.file.close() self.startButton.setEnabled(True) self.serverStatusLabel.setText("Logger ready") def displayError(self, socketError): if socketError == QTcpSocket.RemoteHostClosedError: return QMessageBox.information( self, "Network error", "The following error occured: %s." % self.tcpServer.errorString()) self.tcpServer.close() self.file.close() self.serverStatusLabel.setText("Logger ready") self.startButton.setEnabled(True)