コード例 #1
0
 def start_program(self, path):
     process = QProcess()
     if os.path.splitext(path)[1] == '.pyw':
         process.startDetached('pythonw', [path], os.path.dirname(path))
     else:
         process.startDetached(path, [], os.path.dirname(path))
     print 'Started {:}'.format(os.path.basename(path))
コード例 #2
0
ファイル: preview.py プロジェクト: JulioCesarCampos/sIBL_GUI
    def viewImages(self, paths, customPreviewer=None):
        """
		This method launches an Ibl Set Images Previewer.

		:param paths: Image paths. ( List )
		:param customPreviewer: Custom previewer. ( String )
		"""

        if customPreviewer:
            previewCommand = self.getProcessCommand(paths, customPreviewer)
            if previewCommand:
                LOGGER.debug("> Current image preview command: '{0}'.".format(
                    previewCommand))
                LOGGER.info(
                    "{0} | Launching Previewer with '{1}' images paths.".
                    format(self.__class__.__name__, ", ".join(paths)))
                editProcess = QProcess()
                editProcess.startDetached(previewCommand)
                return True
            else:
                raise Exception(
                    "{0} | Exception raised: No suitable process command given!"
                    .format(self.__class__.__name__))
        else:
            if not len(self.__imagesPreviewers
                       ) >= self.__maximumImagesPreviewersInstances:
                return self.getImagesPreviewer(paths)
            else:
                LOGGER.warning(
                    "!> {0} | You can only launch '{1}' images Previewer instances at same time!"
                    .format(self.__class__.__name__,
                            self.__maximumImagesPreviewersInstances))
コード例 #3
0
ファイル: utils.py プロジェクト: jpburstrom/sampleman
def open_with(app, file):
    """Open file with app."""

    if sys.platform == "darwin":
        QProcess.startDetached("open", [file, "-a", app])
    else:
        QProcess.startDetached(app, [file])
コード例 #4
0
ファイル: preview.py プロジェクト: JulioCesarCampos/sIBL_GUI
	def viewImages(self, paths, customPreviewer=None):
		"""
		This method launches an Ibl Set Images Previewer.

		:param paths: Image paths. ( List )
		:param customPreviewer: Custom previewer. ( String )
		"""

		if customPreviewer:
			previewCommand = self.getProcessCommand(paths, customPreviewer)
			if previewCommand:
				LOGGER.debug("> Current image preview command: '{0}'.".format(previewCommand))
				LOGGER.info("{0} | Launching Previewer with '{1}' images paths.".format(self.__class__.__name__,
																						", ".join(paths)))
				editProcess = QProcess()
				editProcess.startDetached(previewCommand)
				return True
			else:
				raise Exception("{0} | Exception raised: No suitable process command given!".format(
				self.__class__.__name__))
		else:
			if not len(self.__imagesPreviewers) >= self.__maximumImagesPreviewersInstances:
				return self.getImagesPreviewer(paths)
			else:
				LOGGER.warning("!> {0} | You can only launch '{1}' images Previewer instances at same time!".format(
				self.__class__.__name__, self.__maximumImagesPreviewersInstances))
コード例 #5
0
	def editPath(self, path, customTextEditor=None):
		"""
		Provides editing capability.

		:param path: Path to edit.
		:type path: unicode
		:param customTextEditor: Custom text editor.
		:type customTextEditor: unicode
		:return: Method success.
		:rtype: bool
		"""

		if customTextEditor:
			editCommand = self.getProcessCommand(path, customTextEditor)
			if editCommand:
				LOGGER.debug("> Current edit command: '{0}'.".format(editCommand))
				LOGGER.info("{0} | Launching text editor with '{1}' path.".format(self.__class__.__name__, path))
				editProcess = QProcess()
				editProcess.startDetached(editCommand)
				return True
			else:
				raise Exception("{0} | Exception raised: No suitable process command given!".format(
				self.__class__.__name__))
		else:
			self.__scriptEditor.loadPath(path) and self.__scriptEditor.restoreDevelopmentLayout()
			return True
コード例 #6
0
    def editPath(self, path, customTextEditor=None):
        """
		Provides editing capability.

		:param path: Path to edit.
		:type path: unicode
		:param customTextEditor: Custom text editor.
		:type customTextEditor: unicode
		:return: Method success.
		:rtype: bool
		"""

        if customTextEditor:
            editCommand = self.getProcessCommand(path, customTextEditor)
            if editCommand:
                LOGGER.debug(
                    "> Current edit command: '{0}'.".format(editCommand))
                LOGGER.info(
                    "{0} | Launching text editor with '{1}' path.".format(
                        self.__class__.__name__, path))
                editProcess = QProcess()
                editProcess.startDetached(editCommand)
                return True
            else:
                raise Exception(
                    "{0} | Exception raised: No suitable process command given!"
                    .format(self.__class__.__name__))
        else:
            self.__scriptEditor.loadPath(
                path) and self.__scriptEditor.restoreDevelopmentLayout()
            return True
コード例 #7
0
ファイル: CWTDM.py プロジェクト: JasonP27/CWTDM
 def witProcess(self):
     self.createButton.setEnabled(0)
     self.createButton.setText("Please Wait")
     os.chdir(module_path(), 'wit')
     command = "wit.exe"
     args =  ["copy", fstPath, "testdisc.wbfs", "--overwrite"] # "--verbose", "--progress"
     process = QProcess(self)
     process.finished.connect(self.onFinished)
     process.startDetached(command, args)
コード例 #8
0
 def auto_spice(self):
     serverIp = "192.168.0.29"
     #serverIp = "192.168.1.32"
     argcList = ["smep://%s/?port=%s" % (serverIp, "5901")] 
     if self.flag:
         print "argcList:%s"  % argcList
         self.flag = False
         os.system("killall window")
         QProcess.startDetached("/opt/ccr-student/window/window", argcList)
コード例 #9
0
ファイル: CWTDM.py プロジェクト: Semuthitam94/CWTDM
 def witProcess(self):
     self.createButton.setEnabled(0)
     self.createButton.setText("Please Wait")
     os.chdir(module_path(), 'wit')
     command = "wit.exe"
     args = ["copy", fstPath, "testdisc.wbfs",
             "--overwrite"]  # "--verbose", "--progress"
     process = QProcess(self)
     process.finished.connect(self.onFinished)
     process.startDetached(command, args)
コード例 #10
0
ファイル: scrGoodbye.py プロジェクト: ademirel/COMAK
class Widget(QtGui.QWidget, Screen):
    title = i18n("More")
    desc = i18n("Congratulations!")

    def __init__(self, *args):
        QtGui.QWidget.__init__(self,None)
        self.ui = Ui_goodbyeWidget()
        self.ui.setupUi(self)
        var=Desktop.common.getLanguage()
        if var == "Turkish" or var == "tr":
            self.helpPageUrl = "http://www.pardus.org.tr/destek"
        else:
            self.helpPageUrl = "http://www.pardus.org.tr/eng/support"

        self.smoltUrl = "http://smolt.pardus.org.tr:8090"

    def on_buttonSystemSettings_clicked(self):
        Desktop.common.systemSettingsButton()

    def on_buttonHelpPages_clicked(self):
        self.procSettings = QProcess()
        if ctx.Pds.session == ctx.pds.Gnome3:
            command = "chromium-browser " + self.helpPageUrl
        else:
            command = "firefox " + self.helpPageUrl
        self.procSettings.start(command)

    def on_buttonSystemSettings_2_clicked(self):
        self.procSettings = QProcess()
        if ctx.Pds.session == ctx.pds.Gnome3:
            command = "chromium-browser " + self.helpPageUrl
        else:
            command = "firefox " + self.smoltUrl
        self.procSettings.start(command)

    def setSmolt(self):
      # Smolt Settings
        if self.smoltSettings["profileSend"]:
            self.procSettings = QProcess()
            command = "smoltSendProfile"
            arguments = ["-a", "--submitOnly"]
            self.procSettings.startDetached(command, arguments)

#       if not self.smoltSettings["profileSend"]:
#            self.ui.smoltGroupBox.hide()
#            self.ui.label.hide()

    def shown(self):
       self.smoltSettings = smoltWidget.Widget.screenSettings
       self.setSmolt()

    def execute(self):
       return True
コード例 #11
0
class Client_Launcher:
    def __init__(self, core_instance, serverslist_instance, server_name):
        #QThread.__init__(self)
        self.core = core_instance
        self.servers_list = serverslist_instance
        self.server_name = str(server_name)
        self.spice_process = QProcess()
        self.core.add_to_disabled(self.server_name)

    def start(self):
        servers = self.servers_list.get_servers()
        server_data = servers[self.server_name]

        # Forming command
        self.command = "/usr/bin/spicec -h {0} -p {1} ".format(server_data["address"], server_data["port"])
        if len(server_data["password"]) != 0:
            self.command += "-w {0} ".format(server_data["password"])

        if server_data["fullscreen"] != "0":
            self.command += "-f "

        if server_data["depth"] == "16 bit":
            self.command += "--color-depth 16"
        else:
            self.command += "--color-depth 32"

        process_state = self.spice_process.startDetached(self.command)
        if process_state:
            watcher = Client_Watcher(self.core, server_data["port"], self.server_name)
            watcher.run()
    def toggleProcess(self, val):
	if val:
		print 'Starting process'
		self.status, self.pid = QProcess.startDetached(self.command, self.args, '.')
		if self.status:
			print 'PID: ', self.pid
			pidFile = open(self.pidFilePath, 'w')
			pidFile.write(str(self.pid))
			pidFile.close()
			self.qbtn.setText('Stop')			
		else:
			self.qbtn.setChecked(False)
			print 'Error: Failed to create process!'
	else:
		print 'Stopping process'
		if self.status:
			# kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI
			try:
				os.kill(self.pid, SIGINT)
				print 'Process stopped!'
				self.status = False
				self.pid = 0
				if os.path.isfile(self.pidFilePath):
                                  os.remove(self.pidFilePath)
                                else:
                                  print 'Error: No PID file with selected name found'
                                self.qbtn.setText('Start')
			except OSError as e:
                                # http://linux.die.net/man/3/kill | see section "Errors"
				if e.errno == 3:        # process was not found
					print 'Error: Process with selected PID not found'
					os.remove(self.pidFilePath)
				else:
                                        print 'Error: Not enough permissions to terminate'
                                        self.qbtn.setChecked(True)
コード例 #13
0
    def toggleProcess(self, val):
        if val:
            print 'Starting process'
            self.status, self.pid = QProcess.startDetached(
                self.command, self.args, '.')
            if self.status:
                print 'PID: ', self.pid
                pidFile = open(self.pidFilePath, 'w')
                pidFile.write(str(self.pid))
                pidFile.close()
                self.qbtn.setText('Stop')
            else:
                self.qbtn.setChecked(False)
                print 'Error: Failed to create process!'
        else:
            print 'Stopping process'
            if self.status:
                # kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI
                success = 1
                try:
                    success = subprocess.call(
                        ['kill', '-SIGINT', str(self.pid)])
                except OSError as e:
                    if e.errno == 3:
                        print 'Error: Process with selected PID not found'

                if success == 0:
                    print 'Process stopped!'
                    self.status = False
                    self.pid = 0
                    os.remove(self.pidFilePath)
                    self.qbtn.setText('Start')
                else:
                    print 'Error: Failed to stop process! It might have been stopped outside this application'
                    self.qbtn.setChecked(True)
コード例 #14
0
    def toggleProcess(self, val):
	if val:
		print 'Starting process'
		self.status, self.pid = QProcess.startDetached(self.command, self.args, '.')
		if self.status:
			print 'PID: ', self.pid
			pidFile = open(self.pidFilePath, 'w')
			pidFile.write(str(self.pid))
			pidFile.close()
			self.qbtn.setText('Stop')			
		else:
			self.qbtn.setChecked(False)
			print 'Error: Failed to create process!'
	else:
		print 'Stopping process'
		if self.status:
			# kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI
			success = 1
			try:
				success = subprocess.call(['kill', '-SIGINT', str(self.pid)])
			except OSError as e:
				if e.errno == 3:
					print 'Error: Process with selected PID not found'

			if success == 0:
				print 'Process stopped!'
				self.status = False
				self.pid = 0
				os.remove(self.pidFilePath)
				self.qbtn.setText('Start')
			else:
				print 'Error: Failed to stop process! It might have been stopped outside this application'
				self.qbtn.setChecked(True)
コード例 #15
0
	def exploreDirectory(self, directory):
		"""
		Provides directory exploring capability.

		:param directory: Folder to explore.
		:type directory: str
		:return: Method success.
		:rtype: bool
		"""

		browserCommand = None

		directory = os.path.normpath(directory)
		if platform.system() == "Windows" or platform.system() == "Microsoft":
			LOGGER.info("{0} | Launching 'explorer.exe' with '{1}'.".format(self.__class__.__name__, directory))
			browserCommand = "explorer.exe \"{0}\"".format(directory)
		elif platform.system() == "Darwin":
			LOGGER.info("{0} | Launching 'Finder' with '{1}'.".format(self.__class__.__name__, directory))
			browserCommand = "open \"{0}\"".format(directory)
		elif platform.system() == "Linux":
			environmentVariable = Environment("PATH")
			paths = environmentVariable.getValue().split(":")

			browserFound = False
			for browser in self.__linuxBrowsers:
				if not browserFound:
					try:
						for path in paths:
							if os.path.exists(os.path.join(path, browser)):
								LOGGER.info("{0} | Launching '{1}' file browser with '{1}'.".format(self.__class__.__name__,
																									browser,
																									directory))
								browserCommand = "\"{0}\" \"{1}\"".format(browser, directory)
								browserFound = True
								raise StopIteration
					except StopIteration:
						pass
				else:
					break

		if browserCommand:
			LOGGER.debug("> Current browser command: '{0}'.".format(browserCommand))
			browserProcess = QProcess()
			browserProcess.startDetached(browserCommand)
		return True
コード例 #16
0
ファイル: desktop_icon.py プロジェクト: OSUser/quickpanel
 def runShortcut(self, index):
     if not index.isValid():
         return False
     shortcut = self.shortcuts[index.row()]
     if shortcut["path"].startswith("special://"):
         if shortcut["path"] == COMPUTER_PATH:
             if os.name == "nt":
                 explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe")
                 return QProcess.startDetached(explorer, ["::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"])
             else:
                 path = "/"
         elif shortcut["path"] == DOCUMENTS_PATH:
             path = QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)
         elif shortcut["path"] == MUSIC_PATH:
             path = QDesktopServices.storageLocation(QDesktopServices.MusicLocation)
         elif shortcut["path"] == PICTURES_PATH:
             path = QDesktopServices.storageLocation(QDesktopServices.PicturesLocation)
         else:
             return False
         if os.name == "nt": #针对windows进行优化
             explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe")
             return QProcess.startDetached(explorer, [path])
         else:
             return QDesktopServices.openUrl(QUrl.fromLocalFile(path))
     else:
         currentDirectory = os.getcwd()
         try:
             if shortcut["dir"] is not None and shortcut["dir"] != "":
                 os.chdir(shortcut["dir"])
             if shortcut["openwith"] is not None and shortcut["openwith"] != "":
                 if not os.path.exists(shortcut["openwith"]):
                     return False
                 return QProcess.startDetached(shortcut["openwith"], [shortcut["path"]])
             else:
                 url = QUrl.fromUserInput(shortcut["path"])
                 if not url.isValid():
                     return False
                 if url.scheme() == "file" and not os.path.exists(url.toLocalFile()):
                     return False
                 return QDesktopServices.openUrl(url)
         except OSError: #raised by chdir()
             pass
         finally:
             os.chdir(currentDirectory)
     return False
コード例 #17
0
	def __runPackagingCommand(self, command_line):
		self.ui.pbCreatePackage.setEnabled(False)
		try:
			logger.info("going to run command: {0}".format(command_line))
			
			proc = QProcess()
			proc.startDetached(command_line)
			proc.waitForFinished(-1)

			# note: you are looking here, probably because the PKG command failed, but it wasn't caught - I've noticed that
			# the waitForFinished() will always return False (the command runs too quick on analysis for example?), and exitStatus()
			# isn't reliable when a failure occurs anyway.  Useless....
			if proc.exitStatus() != QProcess.NormalExit:
				QMessageBox.critical(self, "Packaging Error", "The packaging process failed to finish properly")
				return False
			return True
		finally:
			self.ui.pbCreatePackage.setEnabled(True)
コード例 #18
0
	def exploreDirectory(self, directory, customBrowser=None):
		"""
		This method provides directory exploring capability.

		:param directory: Directory to explore. ( String )
		:param customBrowser: Custom browser. ( String )
		:return: Method success. ( Boolean )
		"""

		browserCommand = self.getProcessCommand(directory, customBrowser)
		if browserCommand:
			LOGGER.debug("> Current browser command: '{0}'.".format(browserCommand))
			LOGGER.info("{0} | Launching file browser with '{1}' directory.".format(self.__class__.__name__, directory))
			browserProcess = QProcess()
			browserProcess.startDetached(browserCommand)
			return True
		else:
			raise Exception("{0} | Exception raised: No suitable process command given!".format(self.__class__.__name__))
コード例 #19
0
	def editFile(self, file):
		"""
		Provides editing capability.

		:param file: File to edit.
		:type file: str
		:return: Method success.
		:rtype: bool
		"""

		editCommand = None

		file = os.path.normpath(file)
		if platform.system() == "Windows" or platform.system() == "Microsoft":
			LOGGER.info("{0} | Launching 'notepad.exe' with '{1}'.".format(self.__class__.__name__, file))
			editCommand = "notepad.exe \"{0}\"".format(file)
		elif platform.system() == "Darwin":
			LOGGER.info("{0} | Launching default text editor with '{1}'.".format(self.__class__.__name__, file))
			editCommand = "open -e \"{0}\"".format(file)
		elif platform.system() == "Linux":
			environmentVariable = Environment("PATH")
			paths = environmentVariable.getValue().split(":")

			editorFound = False
			for editor in self.__linuxTextEditors:
				if not editorFound:
					try:
						for path in paths:
							if os.path.exists(os.path.join(path, editor)):
								LOGGER.info("{0} | Launching '{1}' text editor with '{2}'.".format(self.__class__.__name__, editor, file))
								editCommand = "\"{0}\" \"{1}\"".format(editor, file)
								editorFound = True
								raise StopIteration
					except StopIteration:
						pass
				else:
					break
		if editCommand:
			LOGGER.debug("> Current edit command: '{0}'.".format(editCommand))
			editProcess = QProcess()
			editProcess.startDetached(editCommand)
		return True
コード例 #20
0
    def editIblSetInSIBLedit(self, path, sIBLedit):
        """
		This method edits given Ibl Set in sIBLedit.

		:param path: Path. ( String )
		:param sIBLedit: sIBLedit. ( String )
		:return: Method success. ( Boolean )
		"""

        editCommand = self.getProcessCommand(path, sIBLedit)
        if editCommand:
            LOGGER.debug("> Current edit command: '{0}'.".format(editCommand))
            LOGGER.info("{0} | Launching 'sIBLedit' with '{1}'.".format(self.__class__.__name__, path))
            editProcess = QProcess()
            editProcess.startDetached(editCommand)
            return True
        else:
            raise Exception(
                "{0} | Exception raised: No suitable process command given!".format(self.__class__.__name__)
            )
コード例 #21
0
def openHTMLFile(htmlfilename):
  settings = QSettings()
  browserPath = settings.value("/Qgis2threejs/browser", "", type=unicode)
  if browserPath == "":
    # open default web browser
    webbrowser.open(htmlfilename, new=2)    # new=2: new tab if possible
  else:
    if not QProcess.startDetached(browserPath, [QUrl.fromLocalFile(htmlfilename).toString()]):
      QMessageBox.warning(None, "Qgis2threejs", "Cannot open browser: %s\nSet correct path in settings dialog." % browserPath)
      return False
  return True
コード例 #22
0
    def __runPackagingCommand(self, command_line):
        self.ui.pbCreatePackage.setEnabled(False)
        try:
            logger.info("going to run command: {0}".format(command_line))

            proc = QProcess()
            proc.startDetached(command_line)
            proc.waitForFinished(-1)

            # note: you are looking here, probably because the PKG command failed, but it wasn't caught - I've noticed that
            # the waitForFinished() will always return False (the command runs too quick on analysis for example?), and exitStatus()
            # isn't reliable when a failure occurs anyway.  Useless....
            if proc.exitStatus() != QProcess.NormalExit:
                QMessageBox.critical(
                    self, "Packaging Error",
                    "The packaging process failed to finish properly")
                return False
            return True
        finally:
            self.ui.pbCreatePackage.setEnabled(True)
コード例 #23
0
    def editIblSetInSIBLedit(self, path, sIBLedit):
        """
		This method edits given Ibl Set in sIBLedit.

		:param path: Path. ( String )
		:param sIBLedit: sIBLedit. ( String )
		:return: Method success. ( Boolean )
		"""

        editCommand = self.getProcessCommand(path, sIBLedit)
        if editCommand:
            LOGGER.debug("> Current edit command: '{0}'.".format(editCommand))
            LOGGER.info("{0} | Launching 'sIBLedit' with '{1}'.".format(
                self.__class__.__name__, path))
            editProcess = QProcess()
            editProcess.startDetached(editCommand)
            return True
        else:
            raise Exception(
                "{0} | Exception raised: No suitable process command given!".
                format(self.__class__.__name__))
コード例 #24
0
ファイル: menu.py プロジェクト: danicampora/ninja-ide-plugins
class Menu(QMenu):

    def __init__(self, locator):
        QMenu.__init__(self, 'Plugin Tools')
        self._locator = locator
        self.explorer_s = self._locator.get_service('explorer')
        self._proc = QProcess(self)
        action_zip = self.addAction('Package This Plugin!')
        self.connect(action_zip, SIGNAL("triggered()"), self.create_zip)
        action_run = self.addAction('Test This Plugin on NINJA-IDE!')
        self.connect(action_run, SIGNAL("triggered()"), self.run_plugin)

    def run_plugin(self):
        p_path = self.explorer_s.get_tree_projects()._get_project_root().path
        ninja_executable = resources.NINJA_EXECUTABLE
        args = ["--plugin", p_path]
        self._proc.startDetached(ninja_executable, args)

    def create_zip(self):
        folder = self.explorer_s.get_tree_projects()._get_project_root().path
        plugin = json_manager.read_ninja_plugin(folder)
        module = os.path.join(folder, plugin.get('module', 'module') + '.zip')
        self.create_zip_file(self.dir_entries(folder, True), module, folder)

    def create_zip_file(self, fileList, archive, relative):
        try:
            zipFile = zipfile.ZipFile(archive, mode='w')
            for fname in fileList:
                zipFile.write(fname, os.path.relpath(fname, relative))
            zipFile.close()

            QMessageBox.information(self, 'Package Created!',
                                    'The package has been created in\nthe '
                                    'project folder.')
        except Exception, reason:
            QMessageBox.information(self, 'Package Failed!',
                                    'The package has not been created '
                                    'in\nthe project folder.')
コード例 #25
0
class Menu(QMenu):
    def __init__(self, locator):
        QMenu.__init__(self, 'Plugin Tools')
        self._locator = locator
        self.explorer_s = self._locator.get_service('explorer')
        self._proc = QProcess(self)
        action_zip = self.addAction('Package This Plugin!')
        self.connect(action_zip, SIGNAL("triggered()"), self.create_zip)
        action_run = self.addAction('Test This Plugin on NINJA-IDE!')
        self.connect(action_run, SIGNAL("triggered()"), self.run_plugin)

    def run_plugin(self):
        p_path = self.explorer_s.get_tree_projects()._get_project_root().path
        ninja_executable = resources.NINJA_EXECUTABLE
        args = ["--plugin", p_path]
        self._proc.startDetached(ninja_executable, args)

    def create_zip(self):
        folder = self.explorer_s.get_tree_projects()._get_project_root().path
        plugin = json_manager.read_ninja_plugin(folder)
        module = os.path.join(folder, plugin.get('module', 'module') + '.zip')
        self.create_zip_file(self.dir_entries(folder, True), module, folder)

    def create_zip_file(self, fileList, archive, relative):
        try:
            zipFile = zipfile.ZipFile(archive, mode='w')
            for fname in fileList:
                zipFile.write(fname, os.path.relpath(fname, relative))
            zipFile.close()

            QMessageBox.information(
                self, 'Package Created!',
                'The package has been created in\nthe '
                'project folder.')
        except Exception, reason:
            QMessageBox.information(
                self, 'Package Failed!', 'The package has not been created '
                'in\nthe project folder.')
コード例 #26
0
def openHTMLFile(htmlfilename):
    url = QUrl.fromLocalFile(htmlfilename).toString()
    settings = QSettings()
    #TODO: Fix UNICODE Bug, for now use UTF-8 instead
    browserPath = settings.value("/PhyloGeoRec/browser", "", type=unicode)
    #browserPath = settings.value("/PhyloGeoRec/browser", "", type="UTF-8")
    if browserPath == "":
        # open default web browser
        webbrowser.open(url, new=2)    # new=2: new tab if possible
    else:
        if not QProcess.startDetached(browserPath, [url]):
            QMessageBox.warning(None, "PhyloGeoRec", "Cannot open browser: %s\nSet correct path in settings dialog." % browserPath)
            return False
    return True
コード例 #27
0
def openHTMLFile(htmlfilename):
    settings = QSettings()
    browserPath = settings.value("/Qgis2threejs/browser", "", type=unicode)
    if browserPath == "":
        # open default web browser
        webbrowser.open(htmlfilename, new=2)  # new=2: new tab if possible
    else:
        if not QProcess.startDetached(
                browserPath, [QUrl.fromLocalFile(htmlfilename).toString()]):
            QMessageBox.warning(
                None, "Qgis2threejs",
                "Cannot open browser: %s\nSet correct path in settings dialog."
                % browserPath)
            return False
    return True
コード例 #28
0
    def toggleProcess(self, val):
	if val:
		print 'Starting process'
		# Note: when roslaunch is terminated all processes spawned by it are also terminated
		# thus even if roscore has been started by the roslaunch process it will too be stopped :)
#		self.status, self.pid = QProcess.startDetached('roslaunch', ['lt', 'talker.launch'], '.') #(self.command, self.args, '.')
		self.status, self.pid = QProcess.startDetached(self.command['command'], self.args, '.') #(self.command, self.args, '.')
		if self.status:
			print 'PID: ', self.pid
			pidFile = open(self.pidFilePath, 'w')
			pidFile.write(str(self.pid))
			pidFile.close()
			self.qbtn.setText('Stop')			
		else:
			self.qbtn.setChecked(False)
			print 'Error: Failed to create process!'
	else:
		print 'Stopping process'
		if self.status:
			# kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI
			self.success = None
			if self.command['command'] == 'rosnode':
				self.success = subprocess.call(['rosnode', 'kill', 'talker'])
			else:
				if check_pid(self.pid):
					self.success = os.kill(self.pid, SIGINT)
				else:
					print 'Error: No process with PID ' + str(self.pid) + ' detected'
				        if os.path.isfile(self.pidFilePath):
						os.remove(self.pidFilePath)
#					self.qbtn.setChecked(True)
			# NOTE: using scripts (rosrun pkg_name script.py) and not launching ROS-confrom nodes creates
			# nodes like "talker_121314_12121414", which are impossible to distinguish without too much
			# fuss and make it really difficult to use 'rosnode kill' hence the requirement to start only
			# nodes that have a simple, distinguishable name so that rosnode kill can be used or use roslaunch
			# and launch files to give proper names

			# == 0 : for subprocess.call() return value | == None : for os.kill() return value (None -> kill was successful)
			if self.success == 0 or self.success == None:
				print 'Process stopped!'
				self.status = False
				self.pid = 0
                                if os.path.isfile(self.pidFilePath):
                                  os.remove(self.pidFilePath)
				self.qbtn.setText('Start')
			else:
				print 'Error: Failed to stop process!'
				self.qbtn.setChecked(True)
コード例 #29
0
 def __startProc(self, applName, *applArgs):
     """
     Private method to start an eric4 application.
     
     @param applName name of the eric4 application script (string)
     @param *applArgs variable list of application arguments
     """
     proc = QProcess()
     applPath = os.path.join(getConfig("ericDir"), applName)
     
     args = QStringList()
     args.append(applPath)
     for arg in applArgs:
         args.append(unicode(arg))
     
     if not os.path.isfile(applPath) or not proc.startDetached(sys.executable, args):
         QMessageBox.critical(self,
             self.trUtf8('Process Generation Error'),
             self.trUtf8(
                 '<p>Could not start the process.<br>'
                 'Ensure that it is available as <b>%1</b>.</p>'
             ).arg(applPath),
             self.trUtf8('OK'))
 def toggleProcess(self, val):
     if val:
         print 'Starting process'
         self.status, self.pid = QProcess.startDetached(
             self.command, self.args, '.')
         if self.status:
             print 'PID: ', self.pid
             pidFile = open(self.pidFilePath, 'w')
             pidFile.write(str(self.pid))
             pidFile.close()
             self.qbtn.setText('Stop')
         else:
             self.qbtn.setChecked(False)
             print 'Error: Failed to create process!'
     else:
         print 'Stopping process'
         if self.status:
             # kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI
             try:
                 os.kill(self.pid, SIGINT)
                 print 'Process stopped!'
                 self.status = False
                 self.pid = 0
                 if os.path.isfile(self.pidFilePath):
                     os.remove(self.pidFilePath)
                 else:
                     print 'Error: No PID file with selected name found'
                 self.qbtn.setText('Start')
             except OSError as e:
                 # http://linux.die.net/man/3/kill | see section "Errors"
                 if e.errno == 3:  # process was not found
                     print 'Error: Process with selected PID not found'
                     os.remove(self.pidFilePath)
                 else:
                     print 'Error: Not enough permissions to terminate'
                     self.qbtn.setChecked(True)
コード例 #31
0
ファイル: msv_m2m_gui.py プロジェクト: fran-jo/SimuGUI
 def browseModels(self):
     dir_to_show = './model/'+ self.txtModelName.text()
     process = QProcess(self)
     process.startDetached("open", [dir_to_show])
     if process.waitForFinished():
         process.close()
コード例 #32
0
import os
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSignal, pyqtSlot, SLOT, SIGNAL, QProcess

if __name__ == "__main__":

    ipop_client = QProcess()
    if os.getuid() == 0:
        print 'sudo rights'
        launched = ipop_client.startDetached("sudo",
                                             ['python', 'test.py', '&'])
        #app.exit()
    else:
        print 'non sudo rights'
        launched = ipop_client.startDetached("gksudo",
                                             ['python', 'test.py', '&'])

    print launched
    #sys.exit(app.exec_())
コード例 #33
0
 def onTrayIconActivated(self, reason):
     # If any click other than a right click
     if reason != QSystemTrayIcon.Context:
         process = QProcess()
         process.startDetached(self.onclick_exec)
         self.stopBlink()
コード例 #34
0
ファイル: launcher.py プロジェクト: HotSushi/IPOP-client
import os
import sys
from PyQt4 import QtCore,QtGui
from PyQt4.QtCore import pyqtSignal,pyqtSlot, SLOT, SIGNAL,QProcess    

if __name__ == "__main__":
    
    ipop_client = QProcess()
    if os.getuid() == 0:
        print 'sudo rights'
        launched = ipop_client.startDetached("sudo", ['python','test.py','&']);
        #app.exit()
    else:
        print 'non sudo rights'
        launched = ipop_client.startDetached("gksudo", ['python','test.py','&']);
    
    print launched    
    #sys.exit(app.exec_())
コード例 #35
0
ファイル: mainWindow.py プロジェクト: pgollor/pyGUI
	def __onHelp(self):
		path = os.path.abspath(os.curdir) + "/doc/index.chm"
		QProcess.startDetached("hh.exe " + path)
コード例 #36
0
            os.kill(pid, 11)
    except:
        print('pid %s killed already' % pid)

p = QProcess()
p.setWorkingDirectory(root_folder)

http_server = ('SimpleHTTPServer', 'http.server')[sys.version_info.major == 3]
args = ('-m', http_server, str(port))

exec_dir = os.path.dirname(sys.executable)
executable = os.path.join(exec_dir,
                          ('python2',
                           'python-qgis.bat')[sys.platform.startswith('win')])

state, pid = p.startDetached(executable, args, root_folder)

print("webserver process started at pid %s, status %s" % (pid, state))

if state:
    s.setValue("X3DProcessing/server_pid", pid)
    iface.messageBar().pushMessage(
        "X3D Processing",
        "webserver process started serving %s from port: %s" %
        (root_folder, port),
        level=QgsMessageBar.INFO,
        duration=10)
'''
def webserver (root, PORT):

    os.chdir(root)