def RunDosCommand(win, command, guiflag=False, redirect=True): """replace $file = current document filename""" if redirect: win.createDosWindow() win.panel.showPage(tr('Dos')) win.dosprompt.SetText('') win.dosprompt.editpoint = 0 win.dosprompt.writeposition = 0 try: win.dosprompt.process = wx.Process(win) win.dosprompt.process.Redirect() if guiflag: win.dosprompt.pid = wx.Execute(command, wx.EXEC_ASYNC | wx.EXEC_NOHIDE, win.dosprompt.process) else: win.dosprompt.pid = wx.Execute(command, wx.EXEC_ASYNC, win.dosprompt.process) win.dosprompt.inputstream = win.dosprompt.process.GetInputStream() win.dosprompt.errorstream = win.dosprompt.process.GetErrorStream() win.dosprompt.outputstream = win.dosprompt.process.GetOutputStream( ) except: win.dosprompt.process = None dlg = wx.MessageDialog( win, tr("There are some problems when running the program!\nPlease run it in shell." ), "Stop running", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() else: wx.Execute(command)
def stampa(nomeDoc, anteprima): # origilale if sys.platform == 'win32': nomeDoc = string.replace(nomeDoc, "/", "\\") import _winreg acrobat = _winreg.QueryValue( _winreg.HKEY_CLASSES_ROOT, 'AcroExch.Document\shell\open\command')[1:-6] if anteprima: cmd = '"%s" %s' else: cmd = '"%s" /p /h %s' pid = wx.Execute(cmd % (acrobat, nomeDoc)) elif wx.Platform == '__WXMAC__': if anteprima: #os.popen("open " + nomeDoc) #pid=wx.Execute("open " + nomeDoc) #da un errore ma funziona #wx.Shell("open "+nomeDoc) #ok funziona pid = os.system("open " + nomeDoc) #os.startfile(nomeDoc) #sembra fuznionare solo su window else: #wx.Execute("lp " + nomeDoc) os.system("lp " + nomeDoc) pid = 0 else: if anteprima: pid = wx.Execute("evince " + nomeDoc) else: wx.Execute("lp-cups " + nomeDoc) pid = 0 f = open(cfg.path_tmp + "pid", "w") f.write(str(pid)) f.close()
def OnOK(self, event): print "in: ", self.inputFile, " out:", self.output, " type:", self.out_format ext = file_ext_type(self.out_format) if (self.inputFile == ''): self.OnFileInError() if (self.output == ''): print "will take care of the output names then" else: pass img = gdal.Open(self.inputFile) infiles = img.GetMetadata("SUBDATASETS") for filename in infiles: system_cmd = "gdalwarp -of " + self.out_format + " -t_srs \"+proj=latlong +ellps=sphere\" " + filename + " " + filename + ".tmp" + ext wx.Execute(system_cmd, True) system_cmd = "gdal_translate -of " + self.out_format + " -a_srs \"EPSG:4326\" -co COMPRESS=YES " + filename + ".tmp" + ext + " " + filename + ext + " ; rm -f " + filename + ".tmp" + ext wx.Execute(system_cmd, True) #imgAr = LoadFile(line) #img = gdal.Open(line) #gt = img.GetGeoTransform() #pj = img.GetProjection() #mtd = img.GetMetadata() #dsc = img.GetDescription() #print pj, "\n", gt, "\n", mtd, "\n", dsc #del img #Free Memory #src_ds = OpenArray( imgAr ) #src_ds.SetGeoTransform( gt ) #src_ds.SetProjection( pj ) #src_ds.SetMetadata(mtd) #src_ds.SetDescription(dsc) #driver = gdal.GetDriverByName( self.out_format ) #driver.CreateCopy( self.output, src_ds ) #del src_ds #Free Memory self.Destroy()
def Execute(self, command, label = None, statustext = "Running script...",beep=False): """Executes a command of which the output will be redirected by OnIdle and OnEndProcess.""" if self.pid is -1: if not label: label = command #give feedback self.AddText('<table bgcolor=#CCCCCC width=100%%><tr><td><TT><img src="%s"> %s</TT></td></tr></table>'%(RUN_ICON,label)) self.SetStatusText(statustext) self.UpdateToolbar() self.Raise() #bind events self.Bind(wx.EVT_IDLE,self.OnIdle) self.Bind(wx.EVT_END_PROCESS,self.OnEndProcess) #create process self.process = wx.Process(self) self.process.Redirect() if info.WIN: self.pid = wx.Execute(command, wx.EXEC_ASYNC | wx.EXEC_NOHIDE, self.process) else: self.pid = wx.Execute(command, wx.EXEC_ASYNC | wx.EXEC_MAKE_GROUP_LEADER, self.process) self.inputstream = self.process.GetInputStream() self.errorstream = self.process.GetErrorStream() self.outputstream = self.process.GetOutputStream() self.inputstream.Write = Write self._check_run(True) self.beep = beep
def cyclops(self, args='', execStart=None, execFinish=None): """ Run the saved application thru Cyclops """ if self.savedAs: cwd = os.path.abspath(os.getcwd()) filename = self.assertLocalFile() os.chdir(os.path.dirname(filename)) page = '' try: name = os.path.basename(filename) report = tempfile.mktemp() # execute Cyclops in Python with module as parameter command = '"%s" "%s" "%s" "%s"' % ( Preferences.getPythonInterpreterPath(), Utils.toPyPath('RunCyclops.py'), name, report) wx.Execute(command, True) # read report that Cyclops generated page = open(report, 'r').read() os.remove(report) finally: os.chdir(cwd) return page else: wx.LogWarning(_('Save before running Cyclops')) raise Exception, _('Not saved yet!')
def open_lyric_file(self, filename): if not self.pconfig.lyric_open_textfile: return # empty basename when the filename is deleted. _dir, fn = os.path.split(filename) if not os.path.splitext(fn)[0]: return filename = os.path.splitext(filename)[0] + ".xml" file_exist = os.path.exists(filename) if not file_exist: if self.pconfig.lyric_copy_from_template and self.pconfig.lyric_template_filename: shutil.copyfile(self.pconfig.lyric_template_filename, filename) file_exist = os.path.exists(filename) cmd = "" if file_exist: if self.pconfig.lyric_application_pathname: cmd = f'"{self.pconfig.lyric_application_pathname}" "{filename}"' else: ft = wx.TheMimeTypesManager.GetFileTypeFromExtension("txt") if ft: cmd = ft.GetOpenCommand( wx.FileType.MessageParameters(filename, "")) if cmd: wx.Execute(cmd, wx.EXEC_ASYNC)
def OnOpenCmdExplorerWindow(win, event=None): filename = win.getCurDoc().getFilename() if not filename: filename = Globals.userpath else: filename = os.path.dirname(filename) wx.Execute(r"explorer.exe /e, %s" % filename)
def connect(self, pythonexec=None, parent=None): "Custom connection method that will start up a new server" # fork a new server process with correct python interpreter (py3/venv) if pythonexec: # warning: this will not work frozen? (ie. py2exe) command = pythonexec + " -u %s --server" % __file__ import wx class MyProcess(wx.Process): "Custom Process Class to handle OnTerminate event method" def OnTerminate(self, pid, status): "Clean up on termination (prevent SEGV!)" def OnClose(self, evt): "Termitate the process on exit" # prevent the server continues running after the IDE closes print("closing pid", self.GetPid()) self.Kill(self.GetPid()) print("killed") self.process = MyProcess(parent) parent.Bind(wx.EVT_CLOSE, self.process.OnClose) #process.Redirect() flags = wx.EXEC_ASYNC if wx.Platform == '__WXMSW__': flags |= wx.EXEC_NOHIDE wx.Execute(command, flags, self.process) return BaseManager.connect(self)
def start(self): """Start a new interpreter process.""" if self.isStarted: # nop if started already return # inform the user that we're starting the console self.txtTerm.Clear() self.txtTerm.WriteText( "Starting Python interpreter session, please wait ...\n") # setup the sub-process wx.BeginBusyCursor() self._process = wx.Process(self) self._process.Redirect() # get the path to the interpreter interpPath = '"' + sys.executable + '"' # start the sub-process self._pid = wx.Execute(r' '.join([interpPath, r'-i']), wx.EXEC_ASYNC, self._process) # bind the event called when the process ends self._process.Bind(wx.EVT_END_PROCESS, self.onTerminate) # clear all text in the widget and display the welcome message self.txtTerm.Clear() self.txtTerm.WriteText( "Python shell in PsychoPy (pid:{}) - type some commands!\n\n". format(self._pid)) # show the subprocess PID for reference self._lastTextPos = self.txtTerm.GetLastPosition() wx.EndBusyCursor()
def run(self): print self.cmd self.pid = wx.Execute(self.cmd, wx.EXEC_ASYNC, self) if not self.pid: wx.MessageDialog(self.win, "Failed to execute command \"%s\". " % self.cmd, "Error", wx.OK | wx.ICON_ERROR)
def run_process(self, pathfilename): """ run a process must be called in main thread """ #scriptArgument = " --config=stdin --result=stdout" scriptArgument = " --config=none --result=stdout" if self.data[PYPATH] is not None: scriptArgument += " --path=%s" % (self.data[PYPATH]) if self.data[TRACE] == TRACE_NONE: scriptArgument += " --trace=none" elif self.data[TRACE] == TRACE_OCTOPYLOG: scriptArgument += " --trace=octopylog" elif self.data[TRACE] == TRACE_TXT: scriptArgument += " --trace=txt" elif self.data[TRACE] == TRACE_OCTOPYLOG_TXT: scriptArgument += " --trace=txt --trace=octopylog" else: assert False if self.data[RUN_TYPE] == RUN_DOC: scriptArgument += " --doc" interpretor = "python -u" cmd = interpretor + " " + pathfilename + scriptArgument self.exit_code = None self.pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) self.log_debug("Process cmd : %s" % cmd) self.log_debug("Process pid : %s" % self.pid)
def ViewURLInBrowser(self, url): if url.find('http:') == -1: url = os.path.normpath(url) if config.prefs.documentationbrowser == '<os.startfile>' and config.PLATFORM_IS_WIN: os.startfile(url) return wx.Execute((config.prefs.documentationbrowser + ' "' + url + '"'), wx.EXEC_ASYNC)
def OnDjangoRunServer(win): oldpath = os.getcwd() try: path = win.getCurrentProjectHome() os.chdir(path) wx.Execute("python manage.py runserver") finally: os.chdir(oldpath)
def OnRestart(self, event): """重启""" argv = list(sys.argv) if os.path.basename(sys.executable) not in argv[0]: argv.insert(0, sys.executable) cmdline = ' '.join(argv) if wx.Execute(cmdline): self.Close()
def OnShellItems(win, event): win.createMessageWindow() eid = event.GetId() index = win.shellmenu_ids.index(eid) command = win.pref.shells[index][1] command = command.replace('$path', os.path.dirname(win.document.filename)) command = command.replace('$file', win.document.filename) wx.Execute(command)
def test_process2(self): flag = False def onEndProcess(evt): flag = True if 'wxMac' not in wx.PlatformInfo: p = wx.Process(self.frame) self.frame.Bind(wx.EVT_END_PROCESS, onEndProcess) wx.Execute('%s %s' % (sys.executable, testscript), callback=p)
def start_local( exe='scsynth', exedir='/Applications/SuperCollider', port=57110, inputs=2, outputs=2, samplerate=44100, ## this is missing from command! verbose=False, ): """ Start an return a local scsynth process. """ fmt = '%(exe)s -u %(port)s -i %(inputs)s -o %(outputs)s' cmd = fmt % locals() fulldir = exedir and os.path.isdir(exedir) if fulldir: cmd = os.path.join(exedir, cmd) print "process.py start_local verbose is", verbose if verbose: print "" print "... ... Starting Supercollider Server ... ..." print "" print cmd if fulldir: _cwd = os.getcwd() os.chdir(exedir) proc = None if os.name == 'nt': if wxparentwin == None: # e for use with wx proc = subprocess.Popen(cmd) else: import wx proc = wx.Process(wxparentwin) proc.Redirect() else: proc = popen2.Popen4(cmd) if fulldir: os.chdir(_cwd) time.sleep(.5) if wxparentwin: ret = wx.Execute(cmd, wx.EXEC_ASYNC, proc) else: ret = proc.poll() if not is_alive(ret): raise OSError('Could not start scsynth, error %i' % ret) return _Instance(proc)
def execute(self, cmd): self.process = wx.Process(self.handler) self.process.Redirect() self.pid = wx.Execute(cmd, wx.EXEC_NOHIDE, self.process) self.inputStream = self.process.GetOutputStream() self.errorStream = self.process.GetErrorStream() self.outputStream = self.process.GetInputStream() #self.OnIdle() wx.WakeUpIdle()
def LongRunning(self): """ This runs in the GUI thread but uses wx.Process and wx.Execute to start and monitor a separate process. """ cmd = 'python -u external_program.py' self.process = wx.Process(self) self.process.Redirect() wx.Execute(cmd, wx.EXEC_ASYNC, self.process)
def reset(self): self.SetReadOnly(0) self.ClearAll() self.commandlist = [] self.current_command_pos = -1 self.process = wx.Process(self) self.process.Redirect() self.pip = wx.Execute(self.parent.setting.CALL_PYTHON, wx.EXEC_ASYNC, self.process) self.input = self.process.GetInputStream() self.output = self.process.GetOutputStream() self.error = self.process.GetErrorStream() self.getOutput()
def OnOpenCmdWindow(win, event=None): filename = win.getCurDoc().getFilename() if not filename: filename = Globals.userpath else: filename = os.path.dirname(filename) if wx.Platform == '__WXMSW__': os.spawnl( os.P_NOWAIT, win.pref.command_line, r" /k %s && cd %s" % (os.path.split(filename)[0][:2], filename)) else: cmdline = win.pref.command_line.replace('{path}', filename) wx.Execute(cmdline)
def OnExecuteBtn(self, evt): cmd = self.cmd.GetValue() self.process = wx.Process(self) self.process.Redirect() pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) self.inp.Enable(True) self.sndBtn.Enable(True) self.termBtn.Enable(True) self.cmd.Enable(False) self.exBtn.Enable(False) self.inp.SetFocus()
def OnExecuteBtn(self, evt): cmd = self.cmd.GetValue() self.process = wx.Process(self) self.process.Redirect(); pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) self.log.write('OnExecuteBtn: "%s" pid: %s\n' % (cmd, pid)) self.inp.Enable(True) self.sndBtn.Enable(True) self.termBtn.Enable(True) self.cmd.Enable(False) self.exBtn.Enable(False) self.inp.SetFocus()
def __init__(self, parent, cmd, end_callback): self.process = wx.Process(parent) self.process.Redirect() self.process.pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) self.b = [] self.last_result = '' if self.process.pid: #what was up with wx.Process.Get*Stream names? self.process._stdin_ = self.process.GetOutputStream() self.process._stdout_ = self.process.GetInputStream() self.process._stderr_ = self.process.GetErrorStream() self.process.Bind(wx.EVT_END_PROCESS, end_callback) return raise StartupError
def OnCommandWindow(self, event): item = self.tree.GetSelection() if not self.is_ok(item): return filename = self.get_node_filename(item) if self.isFile(item): item = self.tree.GetItemParent(item) filename = self.get_node_filename(item) if wx.Platform == '__WXMSW__': os.spawnl( os.P_NOWAIT, self.pref.command_line, r" /k %s && cd %s" % (os.path.split(filename)[0][:2], filename)) else: cmdline = self.pref.command_line.replace('{path}', filename) wx.Execute(cmdline)
def ExternExecute(self, _parentWin, cmd, address, port, **kargs): call = self.GetCfgString(cmd) call = call.replace("%h", address) call = call.replace("%p", str(port)) user = kargs.get('user') if user != None: call = call.replace("%u", user) password = kargs.get('password', "") if password != None: call = call.replace("%P", password) logger.debug("ExternCall %s", call) pid = wx.Execute(call) return pid
def Start_Debug_Application ( self, filename ) : if not ( self.filename ) and filename : ##filename = '../PyLab_Works/test_IDE.py' filename = '../PyLab_Works/test_IDE.py' self.filename = filename #print 'FF',filename debugger = 'pdb_my' #'../Lib_Extensions' #'../Lib_Extensions/my_pdb.py' cmd = 'python -u -m ' + debugger + ' ' + filename self.process = wx.Process ( self.Owner ) #self.process.OnTerminate = self.My_Terminate self.process.Redirect() pid = wx.Execute ( cmd, wx.EXEC_ASYNC, self.process ) self.Started = True
def startWebHelp(self): ''' This method start web server for eclipse help . http://localhost:5000/ ''' try: process = wx.Process(self) process.Redirect() dirPath = os.path.dirname(os.path.realpath(__file__)) filePath = os.path.join(dirPath, '..', '..', '..', '..', 'web', 'HelpWeb.py') logger.debug(dirPath) cmd = f'python {filePath}' pid = wx.Execute(cmd, wx.EXEC_ASYNC, process) logger.debug(f'executing: {cmd} pid: {pid}') except Exception as e: logger.error(e)
def EditWith(self, editor): assert self.temppath == None if self.path: path = self.path else: self.temppath = GenerateTempFilePath(self.editor.GetValue()) path = self.temppath assert self.path != None or self.temppath != None assert path != None cmd = editor % path self.process = wx.Process(self) pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) if pid: self.LockEditor() else: # can't find program self.temppath = None self.process.Destroy()
def RunCmd(self, command, statustext="Running Command", pagetext="Prompt", redin="", redout="", rederr=""): ''' process = wx.Process(self) if type(command) == unicode: command = command.encode(wx.GetDefaultPyEncoding()) wx.Execute(command, wx.EXEC_ASYNC , process) ''' self.txtPrompt.SetReadOnly(0) self.txtPrompt.SetText(command + '\n') self.txtPrompt.SetScrollWidth(1) self.txtPrompt.editpoint = self.txtPrompt.GetLength() self.txtPrompt.GotoPos(self.txtPrompt.editpoint) self.SetStatusText(statustext, 2) self.txtPrompt.process = wx.Process(self) self.txtPrompt.process.Redirect() self.txtPrompt.pid = wx.Execute(command, wx.EXEC_ASYNC | wx.EXEC_NOHIDE, self.txtPrompt.process) ''' if self.PLATFORM_IS_WIN: self.txtPrompt.pid = wx.Execute(command, wx.EXEC_ASYNC | wx.EXEC_NOHIDE, self.txtPrompt.process) else: self.txtPrompt.pid = wx.Execute(command, wx.EXEC_ASYNC, self.txtPrompt.process) ''' self.txtPrompt.inputstream = self.txtPrompt.process.GetInputStream() self.txtPrompt.errorstream = self.txtPrompt.process.GetErrorStream() self.txtPrompt.outputstream = self.txtPrompt.process.GetOutputStream() self.txtPrompt.process.redirectOut = redout self.txtPrompt.process.redirectErr = rederr self.txtPrompt.SetFocus()