Example #1
0
 def cxfreeze_build(source_name, source_folder, working_dir, project_name, build_target, includes_folder, setup_file, buttons_to_disable, cur_self):
     try:
         for button in buttons_to_disable:
             button.setDisabled(True)
         
         #Создаем временную папку по пути working_dir и компилируем в ней проект
         os.chdir(working_dir)
         shutil.rmtree('tmp2', ignore_errors=True)
         try:
             shutil.copytree(source_folder, 'tmp2')
         except Exception:
             shutil.rmtree('tmp2', ignore_errors=True)
             shutil.copytree(source_folder, 'tmp2')
         os.chdir('tmp2')
         shutil.copyfile(setup_file, 'setup.py')
         path = os.getcwd()
         command = str(sys.executable) + ' setup.py build'
     
     except Exception:
         Message.errorMessage(cur_self, ' ', 'Unknown error ocurred.\nYou can try to restart application.', os.path.join(working_dir, 'Resources', 'empt.ico'))
         os.chdir(working_dir)
         shutil.rmtree('tmp2', ignore_errors=True)
         for button in buttons_to_disable:
             button.setDisabled(False)
         return
     
     
     #Исполняем команду компиляции, выводя логи в QTextEdit
     cur_self.log = BuildLog(command, Builder._cxfreeze_continue, working_dir, buttons_to_disable,
                    [source_name, source_folder, working_dir, project_name, build_target, includes_folder, setup_file, buttons_to_disable, cur_self, path])
Example #2
0
    def chooseSetupFile(self):
        dial = QFileDialog()
        file = None

        try:
            if self.firstOpen:
                name = dial.getOpenFileName(self, 'Choose file',
                                            QDir.homePath())
                self.firstOpen = False
            else:
                name = dial.getOpenFileName(self, 'Choose file')
            file = str(
                name
            )[2:-6 - self.
              filepathStrNum]  #('C:/Users/Nikita/Desktop/spiral iz chiesl.py', '')
            file = file.replace('/', os.path.sep)
        except Exception:
            dial.accept()
            return

        if file:
            if os.path.basename(file).split('.')[1] != 'py':
                Message.warningMessage(self, ' ', 'Setup file must be .py')
            else:
                self.cxbldle.setText(file)
Example #3
0
    def addSourceFile(self):
        #Т.к. файл с исходным кодом может быть лишь один, нужно удалить выбранный
        #чтобы выбрать новый
        if self.lt.count() != 0:
            item = self.lt.item(0)
            os.remove(os.path.join('tmp', str(item.text())))
            self.lt.takeItem(self.lt.row(item))

        dial = QFileDialog()

        #Получение нужного для добавления файла
        try:
            if self.firstOpen:
                name = dial.getOpenFileName(self, "Choose file",
                                            QDir.homePath())
                self.firstOpen = False
            else:
                name = dial.getOpenFileName(self, "Choose file")
            file = str(
                name
            )[2:-6 - self.
              filepathStrNum]  #('C:/Users/Nikita/Desktop/spiral iz chiesl.py', '')
            file = file.replace('/', os.path.sep)
            parts = file.split(os.path.sep)
            self.fullsource = file
            if not (('.py' in parts[-1]) or
                    ('pyw' in parts[-1])):  #Проверка верности расширения файла
                if file:
                    #self.warnlbl.setText('Source file must be .py or .pyw')
                    Message.warningMessage(self, ' ',
                                           'Source file must be .py')

                self.source = None

                return
            shutil.copyfile(file, os.path.join(
                'tmp', parts[-1]))  #parts[-1] Собственно имя файла
        except Exception:
            dial.accept()
            return
        else:
            self.source = parts[-1]
            #self.warnlbl.setText('                                                                    ')

        #Получение нужной иконки исходя из расширения файла
        ext = '.' + parts[-1].split('.')[1]
        try:
            iconpath = self.extensions[ext]
        except Exception:
            iconpath = os.path.join(self.resourceFolder, 'blank.ico')

        a = QListWidgetItem(parts[-1])
        a.setIcon(QIcon(iconpath))
        a.setSizeHint(
            QSize(100 / 1920 * self.screenWidth,
                  35 / 1080 * self.screenHeight))
        a.setFlags(a.flags() and Qt.ItemIsEnabled)
        self.lt.addItem(a)
Example #4
0
 def readStdError(self):
     try:
         self.edit.append(
             bytes(
                 self.buildProcess.readAllStandardError()).decode('utf-8'))
     except Exception:
         Message.errorMessage(
             self, ' ',
             'Unknown error ocurred.\nYou can try to restart application.')
 def setUp(self):
     self.incident_type = IncidentType.GAS_LEAK_CONTROL
     self.region = Region.CS
     incident1 = Incident(incident_time=timezone.now(),
                          incident_region=self.region.value,
                          incident_category=self.incident_type.value,
                          incident_status=IncidentStatus.NEW.value)
     incident1.save()
     self.message_new = Message(incident1.id, IncidentStatus.NEW)
     self.message_resolved = Message(incident1.id, IncidentStatus.RESOLVED)
Example #6
0
    def onFinished(self):
        if self.killed:  #Поток прекращен вручную
            return

        if self.box:
            self.box.done(0)

        self.finished = True
        #Передача управления вызвавшей функции
        self.callback(*self.args)
        Message.infoMessage(
            self, ' ', 'Finished. You can now check log for errors.',
            QIcon(os.path.join(self.projectDir, 'Resources', 'empt.ico')))
Example #7
0
 def openInIdle(current_self, fullsource):
     python = os.path.dirname(sys.executable)
     idle = os.path.join(python, "Lib", "idlelib") #Директория с idle
     
     if os.path.isdir(idle):
         if 'idle.bat' in os.listdir(idle):
             idle = os.path.join(idle, 'idle.bat')
             
             try: 
                 command = idle + (' "%s"' % fullsource)
                 result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Что-то типа:  ...\\idle.bat ...\\(source).py
                 time.sleep(IdleOpener.sleepTime) #Ждем sleepTime и проверяем, смог ли запуститься процесс
                 if result.poll(): #result.poll() - процесс не работает
                     Message.errorMessage(current_self, "Fail", "Failed to open IDLE") 
             except Exception:
                 pass
             
         elif 'idle.py' in os.listdir(idle):
             idle = os.path.join(idle, 'idle.py')
             
             try:
                 command = idle + (' "%s"' % fullsource)
                 result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Что-то типа:  ...\\idle.py ...\\(source).py
                 time.sleep(IdleOpener.sleepTime)
                 if result.poll():
                     Message.errorMessage(current_self, "Fail", "Failed to open IDLE") 
             except Exception:
                 pass
         else:
             try:
                 command = 'idle3' + (' "%s"' % fullsource)
                 result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
                 time.sleep(IdleOpener.sleepTime)
                 if result.poll():
                     try:
                         command = 'idle' + (' "%s"' % fullsource)
                         result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
                         time.sleep(IdleOpener.sleepTime)
                         if result.poll():
                             Message.errorMessage(current_self, "Fail", "Failed to open IDLE") 
                     except Exception:
                         pass
             except Exception:
                 pass
     else:
         try:
             command = 'idle3' + (' "%s"' % fullsource)
             result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
             time.sleep(IdleOpener.sleepTime)
             if result.poll():
                 try:
                     command = 'idle' + (' "%s"' % fullsource)
                     result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
                     time.sleep(IdleOpener.sleepTime)
                     if result.poll():
                         Message.errorMessage(current_self, "Fail", "Failed to open IDLE")
                 except Exception:
                     pass
         except Exception:
             pass
Example #8
0
def detail(request, incident_id):
    try:
        incident = Incident.objects.get(id=incident_id)
        form = ContactForm3(request.POST)
        if request.method == 'POST':
            if form.is_valid():

                incident = Incident.objects.get(id=incident_id)
                incident.incident_status = form.cleaned_data['incident_status']
                incident.save()

                message = Message(
                    incident.id,
                    IncidentStatus.from_str(incident.incident_status))
                info_dist = InformationDistributor.get_instance()
                info_dist.distribute(message)

                context = {'form': form, 'incident': incident}
                return render(request, 'statustrack/detail.html', context)
        else:
            form = ContactForm3()
            context = {'form': form, 'incident': incident}
            return render(request, 'statustrack/detail.html', context)

    except Incident.DoesNotExist:
        raise Http404("Incident does not exist")
 def setUp(self):
     incident1 = Incident(
         incident_time=timezone.now(),
         incident_region=Region.SE.value,
         incident_category=IncidentType.GAS_LEAK_CONTROL.value,
         incident_status=IncidentStatus.RESOLVED.value)
     incident1.save()
     self.message = Message(incident1.id, incident1.incident_status)
 def setUp(self):
     incident1 = Incident(
         incident_time=timezone.now(),
         incident_region=Region.NE.value,
         incident_category=IncidentType.RESCUE_AND_EVACUATION.value,
         incident_status=IncidentStatus.NEW.value)
     incident1.save()
     self.message = Message(incident1.id, incident1.incident_status)
Example #11
0
    def createSetupFile(self):
        startDir = os.getcwd(
        )  #После работы необходимо будет вернуться в директорию, в которой мы находились на моменты вызова метода
        try:
            os.chdir(os.path.join(self.projectDir, 'tmp'))

            if "setup.py" in os.listdir(os.getcwd()):
                os.chdir(startDir)
                Message.warningMessage(self, " ",
                                       "Setup file is already created")
                return

            with open('setup.py', 'w') as _:
                pass

            self.cxbldle.setText(os.path.join(os.getcwd(), 'setup.py'))

            self.openSetupInIDLE()
            os.chdir(startDir)  #Возврат в стартовую директорию
        except Exception:
            os.chdir(startDir)
Example #12
0
    def okay(self):
        if str(self.bldbox.currentText()) == 'PyInstaller':
            curdir = os.getcwd()

            #удаляем setup файл если он остался после работы с cx_Freeze
            try:
                os.chdir(os.path.join(self.projectDir, 'tmp'))
                os.remove('setup.py')
                os.chdir(curdir)
            except Exception:
                os.chdir(curdir)

            self.le.setText('PyInstaller')

            with open(os.path.join('data', 'build_settings.pkl'), 'wb') as fl:
                info = ['PyInstaller', str(self.instbldle.text())]
                pickle.dump(info, fl)

            self.done(0)

        elif str(self.bldbox.currentText()) == 'cx_Freeze':
            path = str(self.cxbldle.text())

            if not path or path.isspace():
                Message.warningMessage(self, ' ',
                                       'You have to specify setup file')
            else:
                self.le.setText('cx_Freeze')
                with open(os.path.join('data', 'build_settings.pkl'),
                          'wb') as fl:
                    info = ['cx_Freeze', path]
                    pickle.dump(info, fl)

                self.done(0)

        else:
            self.done(0)
Example #13
0
def incidentCreation(request):
    if request.method == 'GET':
        form = ContactForm2(request.GET)
        print("The incident creation function is called")
        print(form.errors.as_data())

        # form is valid
        if form.is_valid():
            print(form.clean())
            incident = Incident()
            print(form.is_valid())

            incident.caller_name = form.cleaned_data['caller_name']
            incident.mobile_number = form.cleaned_data['mobile_number']
            incident.incident_location = form.cleaned_data['incident_location']
            incident.incident_region = form.cleaned_data['incident_region']
            incident.incident_category = form.cleaned_data['incident_category']
            incident.incident_type = form.cleaned_data['incident_type']
            incident.incident_description = form.cleaned_data[
                'incident_description']

            if incident.incident_category == 'Emergency Ambulance':
                incident.incident_department = 'Singapore Civil Defence Force'
            if incident.incident_category == 'Rescue and Evacuation':
                incident.incident_department = 'Singapore Civil Defence Force'
            if incident.incident_category == 'Fire Fighting':
                incident.incident_department = 'Singapore Civil Defence Force'
            if incident.incident_category == 'Gas Leak Control':
                incident.incident_department = 'Singapore Power'

            incident.save()

            message = Message(incident.id, IncidentStatus.NEW)
            info_dist = InformationDistributor.get_instance()
            info_dist.distribute(message)

            # print("A new incident is saved\n\n\n\n")
            # print(incident.errors.as_json())
            # return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            # return render_to_response('/callcentre/',{'form':form},RequestContext(request))
            return HttpResponseRedirect('/callcentre/')
        else:
            form = ContactForm2()
            return render_to_response('callcentre/incidentCreation.html',
                                      {'form': form}, RequestContext(request))
Example #14
0
def statusTrack(request):
    if request.method == 'GET':
        form = ContactForm3(request.GET)
        if form.is_valid():
            # print("The form is valid\n\n\n\n")
            incident = Incident.objects.get(id=5)
            incident.incident_status = form.cleaned_data['incident_status']
            incident.save()

            message = Message(
                incident.id, IncidentStatus.from_str(incident.incident_status))
            info_dist = InformationDistributor.get_instance()
            info_dist.distribute(message)

            # print("A new incident is saved\n\n\n\n")
            return render_to_response('statustrack/statustrack_home.html',
                                      {'form': form}, RequestContext(request))
        else:
            form = ContactForm3()
            return render_to_response('statustrack/statustrack_home.html',
                                      {'form': form}, RequestContext(request))
Example #15
0
    def build(self):
        missing = []

        if (self.le.text() == '') or (self.le.text().isspace()):
            missing.append("Project name")

        if (self.source is None):
            missing.append("Source file")

        if not hasattr(
                self, 'folder'
        ):  #folder - папка в которую нужно будет перенести скомпилированный проект
            missing.append("Target folder")

        if (not self.toolle.text()):
            missing.append("Build tool")

        if any(missing):
            warning_text = 'You have to specify:\n'
            for i in range(len(missing) - 1):
                warning_text += missing[i] + '\n'

            warning_text += missing[-1]

            Message.warningMessage(self, ' ', warning_text)
            return

        src = os.path.join(self.projectDir, 'tmp')
        build_info = None
        btns_to_disable = [
            self.buildbtn, self.settingsbtn, self.choosebtn,
            self.choosefoldbtn, self.addbtn, self.delbtn
        ]

        try:
            f = open(os.path.join('data', 'build_settings.pkl'), 'rb')
            build_info = pickle.load(f)
            f.close()
        except Exception:
            try:
                f.close()
            except Exception:
                pass

        try:
            shutil.copyfile(
                self.fullsource, os.path.join('tmp', self.source)
            )  # Повторно скопировать файл с исходным кодом в папку с проектом
            pass  # на случай его изменения
        except Exception:
            pass

        if build_info:
            if build_info[0] == 'PyInstaller':

                Builder.pyinstaller_build(source_name=self.source,
                                          source_folder=src,
                                          working_dir=self.projectDir,
                                          project_name=self.le.text(),
                                          build_target=self.folder,
                                          includes_folder=src,
                                          build_options=build_info[1],
                                          buttons_to_disable=btns_to_disable,
                                          cur_self=self)

            elif build_info[0] == 'cx_Freeze':

                Builder.cxfreeze_build(source_name=self.source,
                                       source_folder=src,
                                       working_dir=self.projectDir,
                                       project_name=self.le.text(),
                                       build_target=self.folder,
                                       includes_folder=src,
                                       setup_file=build_info[1],
                                       buttons_to_disable=btns_to_disable,
                                       cur_self=self)
            else:
                pass