def __runCommand(d): l3pApp = os.path.join(config.L3PPath ,'l3p.exe').replace("\\", "/") if not os.path.isfile(l3pApp): error_message = "Error: Could not find L3P.exe in %s - aborting image generation" % os.path.dirname(l3pApp) LicHelpers.writeLogEntry(error_message) print error_message return args = [l3pApp] mode = os.P_WAIT for key, value in d.items(): command = l3pCommands[key] if command: args.append(command[0] + command[1](value)) else: if key == 'inFile': args.insert(1, value) # Ensure input file is first command (after l3p.exe itself) else: args.append(value) if config.writeL3PActivity: LicHelpers.writeLogAccess(" ".join(args)) if sys.platform == 'win32': mode = os.P_DETACH os.spawnv(mode, l3pApp, args)
def _reload(): global _reload_attempted _reload_attempted = True for fn in _reload_hooks: fn() if hasattr(signal, "setitimer"): # Clear the alarm signal set by # ioloop.set_blocking_log_threshold so it doesn't fire # after the exec. signal.setitimer(signal.ITIMER_REAL, 0, 0) if sys.platform == 'win32': # os.execv is broken on Windows and can't properly parse command line # arguments and executable name if they contain whitespaces. subprocess # fixes that behavior. subprocess.Popen([sys.executable] + sys.argv) sys.exit(0) else: try: os.execv(sys.executable, [sys.executable] + sys.argv) except OSError: # Mac OS X versions prior to 10.6 do not support execv in # a process that contains multiple threads. Instead of # re-executing in the current process, start a new one # and cause the current process to exit. This isn't # ideal since the new process is detached from the parent # terminal and thus cannot easily be killed with ctrl-C, # but it's better than not being able to autoreload at # all. # Unfortunately the errno returned in this case does not # appear to be consistent, so we can't easily check for # this error specifically. os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + sys.argv) sys.exit(0)
def start(self): if not self.args: args = [self.name, "-d", "-r", self.root] else: args = [self.name] + self.args print("Starting %s %s" % (self.kind, self.name)) try: import win32process import win32con args = " ".join([self._quote(x) for x in args]) self.proc_handle = ( win32process.CreateProcess( self._quote(self.path), args, None, None, 0, win32con.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO(), ) )[0] except ImportError: os.spawnv(os.P_NOWAIT, self.path, args)
def client_installer( type, current, previous=None, test=False): verbose( 'Running %s installer' % type, False ) if not os.path.exists( exec_inno ): return if test: sufix = '_test' else: sufix = '' args = [] args.append( os.path.basename( exec_inno ) ) args.append( '"/dVERSION_NUMBER=%s"' % current ) args.append( '"/dVERSION_NUMBER_READABLE=v%s.%s"' % ( current[0], current[-3:] ) ) args.append( '"/dDOT_VERSION_NUMBER=%s"' % '.'.join(chunked(current,1)) ) args.append( '"/dOLD_VERSION_NUMBER=%s"' % previous ) args.append( '"/dOLD_VERSION_NUMBER_READABLE=v%s.%s"' % ( previous[0], previous[-3:] ) ) args.append( '"/dSETUP_TYPE=%s"' % type ) args.append( '"/dFILE_PATH=%s"' % os.path.abspath( os.path.join( builds_path, type ) ) ) args.append( '"/dMOD_PATH=pr%s"' % sufix ) if options['password']: args.append( '"/dPASSWORD=%s"' % options['password'] ) args.append( '"/o%s"' % os.path.abspath( builds_path ) ) args.append( '"/q"' ) args.append( '"%s"' % os.path.abspath( installer_path ) ) os.spawnv(os.P_WAIT, exec_inno, args)
def connect(args = [], path = '', wait = 0): """Deze functie maakt het mogelijk om openoffice vanaf de python-interpeter te starten en te bedienen. path is het pad naar OpenOffice en args een list van command-line argumenten. wait is het aantal seconden dat deze functie wacht met retourneren wanneer hij klaar is. Dit is handig wanneer je bestanden aan het laden bent, wat de OOConext is pas bruikbaar wanneer dat bestand geladen is. """ if not path: path = getoopath() exe = os.path.join(path, 'scalc') if sys.platform.startswith('win'): exe += '.exe' command = [exe, '-accept=pipe,name=unopipe;urp;'] command.extend(args) os.spawnv(os.P_NOWAIT, exe, command) xlc = uno.getComponentContext() resolver = xlc.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', xlc) con = 'uno:pipe,name=unopipe;urp;StarOffice.ComponentContext' for i in range(20): try: print 'Poging %i' % i ctx = resolver.resolve(con) OOContext(ctx) if wait: print 'Even wachten...' sleep(wait) print 'Gelukt' return except: sleep(0.5) print 'Mislukt'
def playVideo(self): """ Starts the video player and initializes the first two sets of frames The following frames are pre processed by the timerEvent """ import os,time self.toggle = "A" self.ButtonPlay.setEnabled(0) self.ButtonLoadVideo.setEnabled(0) self.ButtonPause.setEnabled(1) self.ButtonDisableVideo.setEnabled(0) self.spinBoxFrame.setEnabled(0) self.horizontalSlider.setEnabled(0) # Process message self.labelFrame.setPixmap(QPixmap()) self.labelFrame.setText(QtGui.QApplication.translate("MainWindow", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;\"><span style=\" font-size:29pt; font-weight:600; color:#ffa500;\"> Please wait ... processing.</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.repaint() # Processing (1st set) argList = ["-an","-i","\"".join(("",self.videofile,"")),"-ss",self.elapsedTime,"-t","00:00:01","-r","30","-y","-s","640x480","frameshots/videoA%d.jpg"] os.waitpid(os.spawnv(os.P_NOWAIT,FFMPEG, argList), 0) # Processing (2nd set) seektime=time.strftime("%H:%M:%S",time.gmtime((self.selectedFrame+30) / FPS)) argList = ["-an","-i","\"".join(("",self.videofile,"")),"-ss",seektime,"-t","00:00:01","-r","30","-y","-s","640x480","frameshots/videoB%d.jpg"] os.spawnv(os.P_NOWAIT,FFMPEG, argList) #Start timer self.timerID = self.startTimer(80) # Timer for the video player; time in ms; 80 is the current maxiumum due to the time ffmpeg needs for processing print "Start Timer: %i" % self.timerID
def do_command( arguments ): print ' '.join( arguments ), '\n' stdout.flush() if "".join( arguments ).find("*") == -1: if spawnv( P_WAIT, P4_PATH, arguments ) != SUCCESS: return FAILURE return SUCCESS walk_set = walk( "" ) path_set = [] for it in walk_set: path_set.append( it[0] ) exit_code = SUCCESS path = get_current_directory() if path[-1:0] != '\\': path += '\\' for it in path_set: chdir( path + it ) if spawnv( P_WAIT, P4_PATH, arguments ) != SUCCESS: exit_code = FAILURE # let it continue chdir( path ) return exit_code
def __runCommand(d): LogFile= open(os.path.join(config.appDataPath(),"activity.log"),"a") l3pApp = os.path.join(config.L3PPath , 'l3p.exe').replace("\\", "/") LibDir = '-ldd%s' % config.LDrawPath if not os.path.isfile(l3pApp): error_message = "Error: Could not find L3P.exe in %s - aborting image generation" % os.path.dirname(l3pApp) LicHelpers.writeLogEntry(error_message) print error_message return args = [l3pApp,LibDir] for key, value in d.items(): command = l3pCommands[key] if command: args.append(command[0] + command[1](value)) else: if key == 'inFile': args.insert(1, value) # Ensure input file is first command (after l3p.exe itself) else: args.append(value) if config.writeL3PActivity: LogFile.write(" ".join(args)+"\n") LogFile.close() os.spawnv(os.P_WAIT, l3pApp, args)
def showPDF(filename, cfgGl, frame): def complain(): wx.MessageBox("PDF viewer application not found.\n\n" "You can change your PDF viewer\n" "settings at File/Settings/Change.", "Error", wx.OK, frame) if not fileExists(cfgGl.pdfViewerPath): complain() return # on Windows, Acrobat complains about "invalid path" if we # give the full path of the program as first arg, so give a # dummy arg. args = ["pdf"] + cfgGl.pdfViewerArgs.split() + [filename] # there's a race condition in checking if the path exists, above, and # using it, below. if the file disappears between those two we get an # OSError exception from spawnv, so we need to catch it and handle it. # TODO: spawnv does not support Unicode paths as of this moment # (Python 2.4). for now, convert it to UTF-8 and hope for the best. try: os.spawnv(os.P_NOWAIT, cfgGl.pdfViewerPath.encode("UTF-8"), args) except OSError: complain()
def main(): # First, we need to open up the server settings prefLocation = path.expanduser("~/Library/Preferences/net.tuneconnect.Server.plist") if not path.exists(prefLocation): # Assume default values for preferences prefs = {'libraryExpiryTime':86400, 'password':'', 'port':4242, 'useLibraryFile':True} else: # Load into a dictionary prefs = NSDictionary.dictionaryWithContentsOfFile_(prefLocation) # Grab the server port port = prefs['port'] # Check if the server is running url = NSURL.URLWithString_('http://localhost:' + str(port) + '/tc.status') stopUrl = NSURL.URLWithString_('http://localhost:' + str(port) + '/tc.shutdownNow') error = None result, error = NSString.stringWithContentsOfURL_encoding_error_(url, NSUTF8StringEncoding) if (result != "Server Running"): # Not running, we're good pass else: # Gotta' stop that server result, error = NSString.stringWithContentsOfURL_encoding_error_(stopUrl, NSUTF8StringEncoding) if (result == None) or (result == ""): # Success! pass else: print "Error: Could not stop server" return # And finally, open the new pane :) spawnv(P_NOWAIT, '/usr/bin/open', ["", "TuneConnect Server.prefPane"])
def getZippedSize(sceneFile): pervDir = os.getcwd() os.chdir("../../../wot.blitz/") outDir = os.getcwd() + "/export_process/" executable = ( "Tools/ResEditor/dava.framework/Tools/ResourceEditor/ResourceEditorQt.app/Contents/MacOS/ResourceEditorQt" ) os.spawnv( os.P_WAIT, executable, [ executable, "-sceneexporter", "-export", "-indir", mapsDir, "-outdir", outDir, "-processfile", sceneFile, "-forceclose", ], ) zipdir(outDir[:-1], "export_process.zip") zipSize = os.path.getsize("export_process.zip") shutil.rmtree(outDir[:-1]) os.remove("export_process.zip") os.chdir(pervDir) return zipSize
def update_and_restart(tempdir): import wx updater = os.path.join(os.getcwd(), "mac_updater.pyc") from Authorization import Authorization, kAuthorizationFlagDestroyRights auth = Authorization(destroyflags=(kAuthorizationFlagDestroyRights,)) try: python = sys.executable pipe = auth.executeWithPrivileges(python, updater, tempdir) output = pipe.read() if output.find("error") != -1: wx.MessageBox(_("Error while updating Digsby. Please restart and try again, or grab the latest version from digsby.com. Digsby will now shut down.")) pipe.close() wx.GetApp().ExitMainLoop() return pipe.close() wx.MessageBox(_("Updated successfully. Digsby now needs to restart.")) os.spawnv(os.P_NOWAIT, python, ["python", updater, "restart"]) wx.GetApp().ExitMainLoop() except: wx.MessageBox(_("Unable to authenticate. Please restart and try again."))
def OnItemActivated(self, event=None): """Launching the utility.""" name = event.GetText() if name in self.data.keys(): u = self.data[name][0] try: if u.lower() == "mish": import mish argsList = self.data[name][1].split() sys_argv_org = sys.argv mish.sys.argv = ["mish"] + argsList print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nMISH output.\n\nArguments: %s\n"%self.arguments.Value mish.callables.main() sys.argv = sys_argv_org # return # <-- bad hack ? cwd = os.getcwd() os.chdir(os.path.dirname(u)) if u.strip('"').strip("'")[-4:].lower() in (".bat", ".cmd", ".btm"): arguments = "" argsList = self.data[name][1].split() if len(argsList) >0: for a in argsList: arguments += " %s"%a os.system(u+arguments) else: arguments = (os.path.basename(u),) + tuple(self.data[name][1].split()) os.spawnv(os.P_NOWAIT, u.strip('"'), arguments) os.chdir(cwd) except Exception, exc: gui.dialog.WarningMessage(self, _("A problem has occured when opening `%s`.\nYou should edit `utils.dcg` and update the corresponding line.\n\nError shouted by OS:\n%s"%(u, exc))) raise exc
def visit(indent, dirname, names): if not os.path.exists(dirname): print( "Directory %s does not exist!" % os.path.abspath(dirname)) return print( "%s%s:" % (' '*indent*4, os.path.abspath(dirname))) for cfile in names: cpath = os.path.abspath(os.path.join(dirname, cfile)) file, ext = os.path.splitext(cfile) if (os.path.isdir(cpath)): if cfile in exclude_dirs: print( "Directory %s skipped..." % os.path.abspath(cpath)) names.remove(cfile) else: next = "" cmd = "" if ext == ".rbm": next = ".rmdl" cmd = "model" if ext == ".rba": next = ".ranm" cmd = "anim" if next != "": nfile = file + next print( "%s%s => %s" % (' '*4*indent, cpath, nfile)) cmdline = '--convert --%s="%s"' %(cmd, cpath) conv = os.path.abspath(convertor) print( conv + " " + cmdline ) os.spawnv( os.P_WAIT, conv, (conv,) + tuple([cmdline]))
def convert_model(self, model_name): model_file = model_name + '.dae' args = [ self.conversion_tool, '--3ds', model_file ] print args os.spawnv(os.P_WAIT, args[0], args) skel_file = model_name + '.skeleton' mesh_file = model_name + '.mesh' args = [ self.conversion_tool, '--3ds', '--base_skeleton', skel_file ] anims = [] model_files = os.listdir(self.conversion_dir) pattern = re.compile(model_name + '_' + '(.*)' + '.dae') for file_name in model_files: match = pattern.match(file_name) if match: anims.append(match.group(1)) for anim in anims: args.append("--animation") args.append(anim) args.append(model_name + '_' + anim + '.dae') args.append('--out_skeleton') args.append(skel_file) args.append(mesh_file) print args os.spawnv(os.P_WAIT, args[0], args) ## Copy the skeleton and mesh into the media tree shutil.copyfile(model_name + '.skeleton', self.media_dir + 'Skeletons/' + model_name + '.skeleton') shutil.copyfile(model_name + '.mesh', self.media_dir + 'Meshes/' + model_name + '.mesh')
def new_spawnv(mode, path, args): ''' os.spawnv(mode, path, args) os.spawnvp(mode, file, args) ''' import os return getattr(os, original_name)(mode, path, patch_args(args))
def visit_directory(arg, dirname, names): global conversionMode, conversionXScale, conversionYScale; (dirhead, dirtail) = os.path.split(dirname); for fullname in names: fullpath = os.path.normpath( dirname + "/"); pathname = fullpath + "/" + fullname; print pathname; if os.path.isdir(pathname): continue; if fullname[0] == '.' or fullname[0] == '$': continue; (name, ext) = os.path.splitext(fullname); supported_exts = [".png"]; if ext in supported_exts: os.spawnv(os.P_WAIT, "./convert.sh", ["", input_resources_directory, output_resources_directory, name + ext , conversionMode, conversionXScale, conversionYScale]); return
def postrun(): listener.setuid(0) try: os.spawnv(os.P_WAIT, '/bin/sh', ['sh', '/etc/init.d/samba4wins', 'stop']) os.spawnv(os.P_WAIT, '/bin/sh', ['sh', '/etc/init.d/samba4wins', 'start']) finally: listener.unsetuid()
def main_convert_graphics(): # it's function for external usage # *************** HERE YOU SHOULD SETUP YOUR OWN PATHS *************** framework_path = { "Darwin": "./../../..", "Windows": "./../../..", "Microsoft": "./../../.." } # *************** HERE YOU SHOULD SETUP YOUR OWN PATHS *************** currentDir = os.getcwd(); output = os.path.realpath(currentDir + "/Data/") print "*** DAVA SDK Launching command line packer - data directory:" + output params = filter(lambda x: x[0] != '-', sys.argv[1:]) #print params flags = sys.argv[1:] #print flags input = os.path.realpath(currentDir + "/TestData/") #print gfxDirs pvrTexToolPathname = framework_path[platform.system()] + "/Tools/Bin/" if (framework_path[platform.system()] != ""): os.chdir(pvrTexToolPathname) params = ["./ResourcePacker", input] + [pvrTexToolPathname] + flags os.spawnv(os.P_WAIT, "./ResourcePacker", params) else: print "Framework path not defined, please define it in dava_framework_path.py" # come back os.chdir(currentDir)
def __runCommand(d): LogFile= open(os.path.join(config.appDataPath(),"activity.log"),"a") POVRayApp = os.path.join(config.POVRayPath, 'pvengine.exe').replace("\\", "/") if not os.path.isfile(POVRayApp): error_message = "Error: Could not find Pov-Ray in %s - aborting image generation" % os.path.dirname(POVRayApp) LicHelpers.writeLogEntry(error_message) print error_message return args = ['"' + POVRayApp + '"'] for key, value in d.items(): command = povCommands[key] if command: args.append(command[0] + command[1](value)) else: if key == 'inFile': args.insert(1, value) # Ensure input file is first command (after pvengine.exe itself) else: args.append(value) if config.writePOVRayActivity: LogFile.write(" ".join(args)+"\n") LogFile.close() os.spawnv(os.P_WAIT, POVRayApp, args)
def fork(args): """Launch a command in the background.""" if os.name in ('nt', 'dos'): # Windows is absolutely insane. # # If we want to launch 'gitk' we have to use the 'sh -c' trick. # # If we want to launch 'git.exe' we have to expand all filenames # after the double-dash. # # os.spawnv wants an absolute path in the command name but not in # the command vector. Wow. enc_args = win32_expand_paths([core.encode(a) for a in args]) abspath = win32_abspath(enc_args[0]) if abspath: # e.g. fork(['git', 'difftool', '--no-prompt', '--', 'path']) return os.spawnv(os.P_NOWAIT, abspath, enc_args) # e.g. fork(['gitk', '--all']) sh_exe = win32_abspath('sh') enc_argv = map(shell_quote, enc_args) cmdstr = ' '.join(enc_argv) cmd = ['sh.exe', '-c', cmdstr] return os.spawnv(os.P_NOWAIT, sh_exe, cmd) else: # Unix is absolutely simple enc_args = [core.encode(a) for a in args] enc_argv = map(shell_quote, enc_args) cmdstr = ' '.join(enc_argv) return os.system(cmdstr + '&')
def _create_users_file(self): "Create users file" htpasswd = os.path.join(self.httpd_dir, 'bin', 'htpasswd.exe') os.spawnv(os.P_WAIT, htpasswd, ['htpasswd.exe', '-mbc', self.httpd_users, 'jrandom', 'rayjandom']) os.spawnv(os.P_WAIT, htpasswd, ['htpasswd.exe', '-mb', self.httpd_users, 'jconstant', 'rayjandom'])
def handler(dn, new, old): global keytab configRegistry = univention.config_registry.ConfigRegistry() configRegistry.load() server_role = configRegistry['server/role'] if server_role == 'domaincontroller_master': if not new.get('krb5Key'): return listener.setuid(0) try: if old: try: os.unlink('/var/lib/univention-heimdal/%s' %old['cn'][0]) except: pass if new: #FIXME: otherwise the keytab entry is duplicated os.spawnv(os.P_WAIT, '/usr/sbin/kadmin', ['kadmin', '-l', 'ext', '--keytab=/var/lib/univention-heimdal/%s' % new['cn'][0], new['krb5PrincipalName'][0]]) try: userID=pwd.getpwnam('%s$'%new['cn'][0])[2] os.chown('/var/lib/univention-heimdal/%s' %new['cn'][0], userID, 0) os.chmod('/var/lib/univention-heimdal/%s' %new['cn'][0],0660) except: pass finally: listener.unsetuid()
def timerEvent(self, e): """ Timer for the video player Current max. speed is 80ms; ffmpeg isn't fast enough for processing """ if self.labelFrame.isEnabled() and self.selectedFrame <= self.maxFrames-1: # Pre processing: if self.selectedFrame%FPS == 1: import os,time seektime=time.strftime("%H:%M:%S",time.gmtime((self.selectedFrame+30) / FPS)) if self.toggle=="A": argList = ["-an","-i","\"".join(("",self.videofile,"")),"-ss",seektime,"-t","00:00:01","-r","30","-y","-s","640x480","frameshots/videoB%d.jpg"] else: # self.toggle="B" argList = ["-an","-i","\"".join(("",self.videofile,"")),"-ss",seektime,"-t","00:00:01","-r","30","-y","-s","640x480","frameshots/videoA%d.jpg"] os.spawnv(os.P_NOWAIT,FFMPEG, argList) # Show image: image = (self.selectedFrame % FPS) + 1 if self.toggle=="A": pixmap = QPixmap("frameshots/videoA%i.jpg" % image) else: # self.toggle="B" pixmap = QPixmap("frameshots/videoB%i.jpg" % image) self.labelFrame.setPixmap(pixmap) self.spinBoxFrame.setValue(self.selectedFrame) self.readFramesForPlot(self.selectedFrame) if self.selectedFrame%30==29: if self.toggle=="A": self.toggle="B" else: self.toggle="A" self.selectedFrame=self.selectedFrame+1 else: self.pauseVideo() pixmap = QPixmap("images/logo_chrome.png") self.labelFrame.setPixmap(pixmap)
def StartRPy(): rpath = vim.eval("g:rplugin_Rgui") rargs = ['"' + rpath + '"'] r_args = vim.eval("g:rplugin_r_args") if r_args != " ": r_args = r_args.split(' ') i = 0 alen = len(r_args) while i < alen: rargs.append(r_args[i]) i = i + 1 kHandle = None keyName = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" try: kHandle = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, keyName, 0, win32con.KEY_READ) except: vim.command("RWarningMsg('Personal folder not found in registry')") if kHandle: i = 0 folder = "none" while folder != "Personal": try: (folder, fpath, vtype) = win32api.RegEnumValue(kHandle, i) except: break i = i + 1 win32api.RegCloseKey(kHandle) if folder == "Personal": rargs.append('HOME="' + fpath + '"') else: vim.command("RWarningMsg('Personal folder not found in registry')") os.spawnv(os.P_NOWAIT, rpath, rargs)
def StartApp(self,path,portNo = 5101): retstr = '' if (self.appSock!=None): return "This object is already in use." a = IsPortAvailable(portNo) if (a==0): retstr = retstr + "Port No: " + repr(portNo) + " is not available\n" portNo = getNextAvailablePort() retstr = retstr + "Using Port No: " + repr(portNo) +" instead.\n" #here try to change dir to the exe path dir. a = rfind(path,"\\") if (a!=-1): if (path[0:a]==''): os.chdir("\\") else: os.chdir(path[0:a]) try: os.spawnv(os.P_DETACH,path,[path,"-pt",repr(portNo)]) except: retstr = retstr + "Could not start the application\n" return retstr retstr1 = self.ConnectToApp1('localhost',portNo,0) retstr = retstr + retstr1
def openmaila(to=None,subject=None,body=None,attachment=None,**kw): message_options=[] if to is not None: to=quote(to) #if " " in to or "<" in to: # to="'"+to+"'" message_options.append("to=%s" % to) if subject is not None: subject=quote(subject) message_options.append("subject=%s" % subject) if body is not None: body="\r\n".join(body.splitlines()) body=quote(body) message_options.append("body=%s" % body) if attachment is not None: attachment=quote(attachment) message_options.append("attachment=%s" % attachment) for kv in kw.items(): message_options.append("%s='%s'" % kv) path=r'C:\Program Files\Mozilla Thunderbird\thunderbird.exe' #cmd="'%s' -compose \"%s\"" % (path,",".join(message_options)) #print cmd #os.system(cmd) args = [path, '-compose', ",".join(message_options)] #print args os.spawnv(os.P_NOWAIT,path,args)
def getZippedSize(sceneFile): pervDir = os.getcwd(); os.chdir("../../../wot.blitz/"); currentDir = os.getcwd(); dataDir = os.path.realpath(currentDir + "/../Data/3d/"); dataSourceDir = os.path.realpath(currentDir + "/DataSource/3d/"); index = dataSourceDir.find(':'); if ( index != -1): dataSourceDir = dataSourceDir[index + 1:]; outDir = os.getcwd() + '/export_process/'; exportDir = os.path.realpath(outDir); index = exportDir.find(':') if ( index != -1): exportDir = exportDir[index + 1:]; executable = executables[platform.system()]; os.spawnv(os.P_WAIT, executable, [executable, '-sceneexporter', '-export', '-indir', dataSourceDir, '-outdir', exportDir, '-processfile', sceneFile, '-forceclose', '-format', formatParam]); zipdir(outDir[:-1], 'export_process.zip'); zipSize = os.path.getsize('export_process.zip'); shutil.rmtree(outDir[:-1]); os.remove('export_process.zip'); os.chdir(pervDir); return zipSize;
def reload_server(io_loop): # wait for other files to be written time.sleep(0.5) for fd in io_loop._handlers.keys(): try: os.close(fd) except: pass if hasattr(signal, "setitimer"): # Clear the alarm signal set by # ioloop.set_blocking_log_threshold so it doesn't fire # after the exec. signal.setitimer(signal.ITIMER_REAL, 0, 0) try: os.execv(sys.executable, [sys.executable] + sys.argv) except OSError: # Mac OS X versions prior to 10.6 do not support execv in # a process that contains multiple threads. Instead of # re-executing in the current process, start a new one # and cause the current process to exit. This isn't # ideal since the new process is detached from the parent # terminal and thus cannot easily be killed with ctrl-C, # but it's better than not being able to autoreload at # all. # Unfortunately the errno returned in this case does not # appear to be consistent, so we can't easily check for # this error specifically. os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + sys.argv) sys.exit(0)
def execute(self, parameters, messages): """The source code of the tool.""" # VARIABLES, PATHS, WORKSPACE # job folder jobID = 'JOB_'+str(parameters[0].value) # tile number tileID = str(parameters[1].value) # job folder location jobfdr = os.path.join(JobLoc,jobID) # MXD path MXDPath = os.path.join(jobfdr,tileID,tileID) # check to see if job folder is present, if not check if read-only is present if not os.path.isdir(jobfdr): MXDPath = os.path.join(jobfdr+'_Readonly',tileID,tileID) # check if ArcMapPath is a valid file if os.path.isfile(ArcMapPath): # check if is a valid mxd path if os.path.isfile(MXDPath+'.mxd'): # open MXD os.spawnv(os.P_NOWAIT, ArcMapPath, ["ArcMap.exe", MXDPath]) arcpy.AddMessage('Opening mxd, please wait...') else: print 'Invalid mxd file path given: \t'+MXDPath arcpy.AddMessage('Invalid mxd file path given: \t'+MXDPath) else: print 'The harcoded ArcMap file path in the script is invalid, please change this to your current ArcMap installation path' arcpy.AddMessage('The harcoded ArcMap file path in the script is invalid, please change this to your current ArcMap installation path') return
def main(*args): # Start HTTP server thread. Note that this and all other comm server # threads should be daemon threads: we'll let them run "forever," # confident that the whole process will terminate when the main thread # terminates, which will be when the test executable child process # terminates. httpThread = TestHTTPServer(name="httpd") httpThread.setDaemon(True) httpThread.start() # choice of os.spawnv(): # - [v vs. l] pass a list of args vs. individual arguments, # - [no p] don't use the PATH because we specifically want to invoke the # executable passed as our first arg, # - [no e] child should inherit this process's environment. debug("Running %s...\n" % (" ".join(args))) sys.stdout.flush() rc = os.spawnv(os.P_WAIT, args[0], args) debug("%s returned %s\n" % (args[0], rc)) return rc
def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0): executable = cmd[0] cmd = _nt_quote_args(cmd) if search_path: # either we find one or it stays the same executable = find_executable(executable) or executable log.info(' '.join([executable] + cmd[1:])) if not dry_run: # spawn for NT requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) except OSError, exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) if rc != 0: # and this reflects the command running but failing raise DistutilsExecError, \ "command '%s' failed with exit status %d" % (cmd[0], rc)
def _create_users_file(self): "Create users file" htpasswd = os.path.join(self.httpd_dir, 'bin', 'htpasswd.exe') # Create the cheapest to compare password form for our testsuite os.spawnv( os.P_WAIT, htpasswd, ['htpasswd.exe', '-bcp', self.httpd_users, 'jrandom', 'rayjandom']) os.spawnv(os.P_WAIT, htpasswd, [ 'htpasswd.exe', '-bp', self.httpd_users, 'jconstant', 'rayjandom' ]) os.spawnv(os.P_WAIT, htpasswd, [ 'htpasswd.exe', '-bp', self.httpd_users, '__dumpster__', '__loadster__' ])
def RunPythonExe(file, *args): fullpath = GetFullPath(file) temppath = System.IO.Path.Combine( sys.prefix, System.IO.FileInfo(fullpath).Name).ToLower() if (fullpath != temppath): System.IO.File.Copy(fullpath, temppath, True) realargs = [temppath] realargs.extend(args) try: retval = os.spawnv(0, temppath, realargs) except: retval = 1 # hack if (fullpath != temppath): DeleteFile(temppath) Assert(not retval)
def upstream_patch(self, input_patch): self.log("Patching source with %s\n" % input_patch) match = re.match( r'(^|.*/)patch-\d+\.\d+\.\d+(-\S+?)?(\.(?P<extension>(bz2|gz)))?$', input_patch) if not match: raise RuntimeError("Can't identify name of patch") cmdline = [] if match.group('extension') == 'bz2': cmdline.append('bzcat') elif match.group('extension') == 'gz': cmdline.append('zcat') else: cmdline.append('cat') cmdline.append(input_patch) cmdline.append( '| (cd %s; patch -p1 -f -s -t --no-backup-if-mismatch)' % os.path.join(self.dir, self.orig)) if os.spawnv(os.P_WAIT, '/bin/sh', ['sh', '-c', ' '.join(cmdline)]): raise RuntimeError("Can't patch source")
def actualSolve(self, lp): """Solve a well formulated lp problem""" if not self.executable(self.path): raise PulpSolverError("PuLP: cannot execute "+self.path) tmpLp, tmpSol = self.create_tmp_files(lp.name, 'lp', 'sol') lp.writeLP(tmpLp, writeSOS = 0) proc = ["glpsol", "--cpxlp", tmpLp, "-o", tmpSol] if not self.mip: proc.append('--nomip') proc.extend(self.options) self.solution_time = clock() if not self.msg: proc[0] = self.path pipe = open(os.devnull, 'w') if operating_system == 'win': # Prevent flashing windows if used from a GUI application startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW rc = subprocess.call(proc, stdout = pipe, stderr = pipe, startupinfo = startupinfo) else: rc = subprocess.call(proc, stdout = pipe, stderr = pipe) if rc: raise PulpSolverError("PuLP: Error while trying to execute "+self.path) pipe.close() else: if os.name != 'nt': rc = os.spawnvp(os.P_WAIT, self.path, proc) else: rc = os.spawnv(os.P_WAIT, self.executable(self.path), proc) if rc == 127: raise PulpSolverError("PuLP: Error while trying to execute "+self.path) self.solution_time += clock() if not os.path.exists(tmpSol): raise PulpSolverError("PuLP: Error while executing "+self.path) status, values = self.readsol(tmpSol) lp.assignVarsVals(values) lp.assignStatus(status) self.delete_tmp_files(tmpLp, tmpSol) return status
def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createCanvas() self.master = master self.spec = [] if (len(sys.argv) > 1 and os.spawnv(os.P_WAIT, "dft", ['dft', sys.argv[1]]) == 0): master.title("Magnitude Spectrum of %s" % sys.argv[1]) f = open("spec.txt") maxi = 0.1 self.sr = float(f.readline()) for line in f: self.spec.append(float(line)) if float(line) > maxi: maxi = float(line) self.max = maxi self.space = self.size / (len(self.spec) + 1) self.draw() else: self.message() self.master.protocol("WM_DELETE_WINDOW", self.quit)
def add_interface(self, brname, ifname): """ Adds an interface to a bridge Keyword arguments: brname -- Bridge name (string, ex: "br0") ifname -- Interface to add to bridge (string, ex: "eth3") """ if brname not in self.options.ignorebridges: brlist = self.list() if ifname not in brlist[brname]: exitcode = os.spawnv(os.P_WAIT, self.options.brctl, [ self.options.brctl, "addif", brname, ifname ] ) else: # Interface is already a member of this bridge, return 0 # anyway. exitcode = 0 else: exitcode = -1 return exitcode
def make_win(dstfile, srclst): f = dstfile + ".zip" try: os.remove(f) except: pass r = 0 l = len(srclst) sl = 20 # chunk size for i in range(0, l - 1, sl): args = ["wzzip", "-r -P " + f] + srclst[i:i + sl] r = os.spawnv(os.P_WAIT, "c:\programme\util\winzip\wzzip", args) if r != 0: break if r == 0: return f else: print "wzzip could not be executed" return ""
def panggil(): try: os_system = str(platform.system()) director = os.path.dirname(os.path.abspath(__file__)) print('[INFO] Retrieved OS Info: ', os_system) if os_system.lower() == 'windows': print("[SYSTEM] Windows Detected") command = "ngrok start --all --config=ngrok.yml" #ngrok = open("ngrok_cmd_fixed.bat","w") #ngrok.write(str(command)) #ngrok.close() os.spawnv(os.P_NOWAIT, "ngrok.exe", ["ngrok.exe", "start", " --config=ngrok.yml", " --all" ]) #i have two account :p os.spawnv(os.P_NOWAIT, "ngrok.exe", ["ngrok.exe", "start", " --config=ngrok2.yml", " --all"]) print("[INFO] App Launched") else: #command = "ngrok start --all --config=ngrok.yml" #ngrok = open("ngrok_cmd_fixed","w") #ngrok.write(str(command)) #ngrok.close() #st = os.stat('ngrok_cmd') #print(st) #os.chmod('ngrok_cmd_fixed', st.st_mode | stat.S_IEXEC) os.spawnv(os.P_NOWAIT, "ngrok", ["ngrok", "start", "--all", "--config", "ngroklin.yml" ]) #i have two account :p os.spawnv(os.P_NOWAIT, "ngrok", ["ngrok", "start", "--all", "--config", "ngrok2lin.yml"]) print("[INFO] App Launched") except (KeyboardInterrupt, Exception) as k: print("[INFO] App Stopped,Closing Mysql Connection") mydb.close() db.commit() db.close() display.stop() sys.exit()
def _StartGroupChildren(cl, wait): """Starts a new instance of the watcher for every node group. """ assert not compat.any( arg.startswith(cli.NODEGROUP_OPT_NAME) for arg in sys.argv) result = cl.QueryGroups([], ["name", "uuid"], False) children = [] for (idx, (name, uuid)) in enumerate(result): args = sys.argv + [cli.NODEGROUP_OPT_NAME, uuid] if idx > 0: # Let's not kill the system time.sleep(CHILD_PROCESS_DELAY) logging.debug("Spawning child for group '%s' (%s), arguments %s", name, uuid, args) try: # TODO: Should utils.StartDaemon be used instead? pid = os.spawnv(os.P_NOWAIT, args[0], args) except Exception: # pylint: disable=W0703 logging.exception("Failed to start child for group '%s' (%s)", name, uuid) else: logging.debug("Started with PID %s", pid) children.append(pid) if wait: for pid in children: logging.debug("Waiting for child PID %s", pid) try: result = utils.RetryOnSignal(os.waitpid, pid, 0) except EnvironmentError, err: result = str(err) logging.debug("Child PID %s exited with status %s", pid, result)
def main(): """ Main routine that delegates all commands to GreatFET subcommands. """ argv = sys.argv[:] # If we don't have a subcommand, abort. if len(argv) < 2: print_usage(argv) sys.exit(errno.EINVAL) # Get the subcommand name. subcommand_name = argv[1] # If help is passed as a special-case subcommand, and we have # more arguments, help the user out by generating a likely-valid help request. if subcommand_name == "help" and len(argv) > 2: subcommand_name = argv[2] argv[1], argv[2] = argv[2], "--help" # Find the binary to execute... binary = find_subcommand(subcommand_name) # If we couldn't find the relevant binary, print a message. if not binary: # If there are words that are similar to the relevant word, suggest them as corrections. corrections = find_corrections_message(subcommand_name) if corrections: print(corrections) print('') sys.exit(errno.EINVAL) # Compute the arguments that should be passed to the subcommand, # which include the subcommand name and all arguments beyond the subcommand. binary_name = os.path.basename(binary) arguments = [binary_name] + argv[2:] # Pass control entirely to the subcommand. sys.exit(os.spawnv(os.P_WAIT, binary, arguments))
def launch_ironpython_changing_extensions(test, add=[], remove=[], additionalScriptParams=()): final = _get_ip_testmode() for param in add: if param not in final: final.append(param) for param in remove: if param in final: pos = final.index(param) if pos != -1: if param in one_arg_params: del final[pos:pos+2] else : del final[pos] params = [sys.executable] params.extend(final) params.append(test) params.extend(additionalScriptParams) print "Starting process: %s" % params return os.spawnv(0, sys.executable, params)
def build_moby_index(moby_txt=MOBY_TXT, index_name=None, index_dir=INDEX_DIR, zet_exe=ZET_EXE, impacts=False): """Build an index of Moby Dick.""" if index_name is None: if impacts: index_name = IMPACT_INDEX_NAME else: index_name = INDEX_NAME if not os.access(zet_exe, os.X_OK): raise MobyTestError("Cannot run the zet program at '%s'" % zet_exe) if not os.access(moby_txt, os.R_OK): raise MobyTestError("Cannot access moby test collection at '%s'" \ % (moby_txt)) args = [zet_exe, "-f", os.path.join(index_dir, index_name), "-i", moby_txt] if impacts: args[1:1] = ["--anh-impact"] ret = os.spawnv(os.P_WAIT, zet_exe, args) if ret != 0: raise MobyTestError("Failed to build index of Moby Dick")
def __init__(self, headless=False): if "UNO_PATH" in os.environ: office = os.environ["UNO_PATH"] else: if platform.startswith("win"): # XXX office = "" else: # Lets hope that works.. office = '/usr/bin' office = os.path.join(office, "soffice") if platform.startswith("win"): office += ".exe" self._pidfile = "/tmp/markup_renderer_OOinstance" #XXX Windows compat needed self._socket = "name=markupRendererPipe" xLocalContext = uno.getComponentContext() self._resolver = xLocalContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", xLocalContext) args = [ "--invisible", "--nologo", "--nodefault", "--norestore", "--nofirststartwizard" ] if headless: args.append("--headless") if platform.startswith("win"): cmdArray = ['"' + office + '"'] else: cmdArray = [office] cmdArray += args + ["--accept=pipe,%s;urp" % self._socket] if (not os.path.isfile(self._pidfile)): self.pid = os.spawnv(os.P_NOWAIT, office, cmdArray) f = open(self._pidfile, "w") f.write(str(self.pid))
def start_ie(logf, args=""): """ Start otimpexp.exe """ _log(logf, log.DEBUG, "В функции start_ie ") try: _log(logf, log.INFO, "Запуск " + str(cfg.ot_ie) + " " + str(args)) exitcode = os.spawnv(os.P_WAIT, cfg.ot_ie, (cfg.ot_ie, args)) _log(logf, log.INFO, "Код возврата [" + str(exitcode) + "]") except: _log( logf, log.ERROR, "Ошибка запуска [" + str(cfg.ot_ie) + " " + str(args)) _log( logf, log.ERROR, "Сообщение системы: " + str("[" + str(sys.exc_info()[0]) + "." + str(sys.exc_info()[1]) + "]")) return -1 # БЛЯДЬ! Hу какого хуя в этой винде прут глюки такие? # Кто же виноват? # time.sleep(10) _log(logf, log.DEBUG, "Выход из функции start_ie ") return exitcode
def hidden_call(executable, arguments): args = [executable] + arguments try: # Using simpscrp is depreciated; remove '_disabled' below to use: import simpscrp_disabled args = ['"' + str(x) + '"' for x in args] call = ' '.join(args) simpscrp.Exec(call, 1) except ImportError: try: import subprocess si = subprocess.STARTUPINFO() # Location of below constants seems to vary from Python # version to version so hardcode them: si.dwFlags = 1 # subprocess.STARTF_USESHOWWINDOW si.wShowWindow = 0 # subprocess.SW_HIDE return subprocess.call(args, startupinfo=si) except ImportError: pid = os.spawnv(os.P_NOWAIT, executable, args) pid, exit_code = os.waitpid(pid, 0) exit_code = exit_code >> 8 return exit_code
def spawn_nt(self, cmd, search_path=1, verbose=0, dry_run=0): executable = cmd[0] if search_path: # either we find one or it stays the same executable = find_executable(executable) or executable print(' '.join([executable] + cmd[1:])) if not dry_run: # spawn for NT requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) except OSError as exc: # this seems to happen when the command isn't found if not DEBUG: cmd = executable raise DistutilsExecError("command %r failed: %s" % (cmd, exc.args[-1])) if rc != 0: # and this reflects the command running but failing if not DEBUG: cmd = executable raise DistutilsExecError( "command %r failed with exit status %d" % (cmd, rc))
def add_promisc_bridge(self, brname, ifname): """ Creates a new bridge, attaches an interface to it and sets the MAC address of the connected interface to FE:FF:FF:FF:FF:FF so traffic can flow freely through the bridge. This seems to be required for use with xen. Keyword arguments: brname -- Bridge name (string, ex: "br0") ifname -- Interface name (string, ex: "eth2") """ addbrret = self.add_bridge(brname) addifret = self.add_interface(brname,ifname) # Set the MAC address of the interface we're adding to the bridge to # FE:FF:FF:FF:FF:FF. This is consistent with the behaviour of the # Xen network-bridge script. setaddrret = os.spawnv(os.P_WAIT, self.options.ip, [ self.options.ip, "link", "set", ifname, "address", "fe:ff:ff:ff:ff:ff" ]) if addbrret or addifret or setaddrret: return -1 else: return 0
def open_file_in_editor(file, hflag=True): #bruce 050913 revised this """ Opens a file in a standard text editor. Error messages go to console and (unless hflag is false) to env.history. """ #bruce 050913 replaced history arg with hflag = True, since all callers passed env.history to history arg. file = os.path.normpath(file) if not os.path.exists(file): msg = "File does not exist: " + file print msg if hflag: env.history.message(redmsg(msg)) return editor_and_args = get_text_editor() # a list of editor name and 0 or more required initial arguments [bruce 050704 revised API] editor = editor_and_args[0] initial_args = list(editor_and_args[1:]) if os.path.exists(editor): args = [editor] + initial_args + [file] if debug_flags.atom_debug: print "editor = ", editor print "Spawnv args are %r" % (args, ) try: # Spawn the editor. kid = os.spawnv(os.P_NOWAIT, editor, args) except: # We had an exception. print_compact_traceback("Exception in editor; continuing: ") msg = "Cannot open file " + file + ". Trouble spawning editor " + editor print msg if hflag: env.history.message(redmsg(msg)) else: msg = "Cannot open file " + file + ". Editor " + editor + " not found." if hflag: env.history.message(redmsg(msg)) return
def __init__(self, port = 9001): threading.Thread.__init__(self) self._port = port self._run = None self._test = None self._totalVariations = 0 self._variationCount = 0 self._value = None self._exception = None self._isFinished = False self._lock = threading.Lock() self._faultCount = 0 self._faultData = [] self.start() # This will never work on Liunx/OS X :) try: params = [ 'explorer', "http://127.0.0.1:"+str(self._port)] ret = os.spawnv(os.P_NOWAIT, "c:/windows/explorer.exe", params ) except: pass
def _run_prog(self, cmdline): 'Execute COMMAND, redirecting standard output and error to the log file.' def restore_streams(stdout, stderr): os.dup2(stdout, 1) os.dup2(stderr, 2) os.close(stdout) os.close(stderr) sys.stdout.flush() sys.stderr.flush() self.log.flush() old_stdout = os.dup(1) old_stderr = os.dup(2) try: os.dup2(self.log.fileno(), 1) os.dup2(self.log.fileno(), 2) rv = os.spawnv(os.P_WAIT, cmdline[0], cmdline) except: restore_streams(old_stdout, old_stderr) raise else: restore_streams(old_stdout, old_stderr) return rv
def test_lp292604(self): '''Test Launchpad bug #292604''' self.listener = os.fork() if self.listener == 0: args = [ '/bin/sh', '-c', 'exec /usr/bin/gnutls-serv --http -p 4433 --x509keyfile /etc/ssl/private/ssl-cert-snakeoil.key --x509certfile /etc/ssl/certs/ssl-cert-snakeoil.pem --x509cafile ./ssl/lp292604-ca-certificate.crt >/dev/null 2>&1' ] os.execv(args[0], args) sys.exit(0) time.sleep(1) rc, report = testlib.cmd(['ping', '-c', '1', 'server']) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) exe = '/usr/bin/gnutls-cli' args = [ '/bin/sh', '-c', 'exec ' + exe + ' -V -p 4433 --insecure server >/dev/null 2>&1' ] pid = os.spawnv(os.P_NOWAIT, args[0], args) time.sleep(2) running = False if (testlib.check_pid(exe, pid)): running = True os.kill(pid, signal.SIGALRM) # kill server now os.kill(self.listener, 15) os.waitpid(self.listener, 0) result = "'%s' died unexpectedly." % (exe) self.assertTrue(running, result)
def test_lp305264(self): '''Test Launchpad bug #305264 - deprecation of rsa/md2 certificates''' self.listener = os.fork() if self.listener == 0: args = [ '/bin/sh', '-c', 'exec /usr/bin/gnutls-serv --http -p 4433 --x509keyfile ./ssl/lp305264/lp305264-key.pem --x509certfile ./ssl/lp305264/lp305264-cert.pem >/dev/null 2>&1' ] os.execv(args[0], args) sys.exit(0) time.sleep(1) rc, report = testlib.cmd(['ping', '-c', '1', 'server']) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) exe = '/usr/bin/gnutls-cli' args = [ '/bin/sh', '-c', 'exec ' + exe + ' -V -p 4433 --x509cafile ./ssl/lp305264/cacert.pem server >/dev/null 2>&1' ] pid = os.spawnv(os.P_NOWAIT, args[0], args) time.sleep(2) running = False if (testlib.check_pid(exe, pid)): running = True os.kill(pid, signal.SIGALRM) # kill server now os.kill(self.listener, 15) os.waitpid(self.listener, 0) result = "'%s' accepted an rsa/md2 certificate." % (exe) self.assertFalse(running, result)
def spawn_program(filename, path=os.path.join(PYTHON_PATH, 'python'), command='python', wait_mode=os.P_WAIT): """ need to enter a single quote follow by double quote eg: '"c:\\data\\example.py"' adding args: eg:'"C:\\SETS Files\\Python\\Examples\\Script1_try.py" 1 2' if error, return one,else return 0 Wait_mode option allow user to specify whether to wait for program to finish or continue with next commands Input in os.P_WAIT(0) or os.P_NOWAIT(1) """ try: results = os.spawnv(wait_mode, path, [command, filename]) finally: if results != 0: print 'Error in running program' return 1 return 0
def tar(self): out = os.path.join("../orig", self.orig_tar) try: os.mkdir("../orig") except OSError: pass try: os.stat(out) raise RuntimeError("Destination already exists") except OSError: pass self.log("Generate tarball %s\n" % out) cmdline = ['tar -czf', out, '-C', self.dir, self.orig] try: if os.spawnv(os.P_WAIT, '/bin/sh', ['sh', '-c', ' '.join(cmdline)]): raise RuntimeError("Can't patch source") os.chmod(out, 0644) except: try: os.unlink(out) except OSError: pass raise
def test_graphserver(): import socket s = socket.socket() s.listen(1) host, port = s.getsockname() # pick a random free port s.close() if hasattr(sys, 'pypy_objspaceclass'): python = 'python' else: python = sys.executable cmdargs = [python, str(pkgdir.join('graphserver.py')), str(port)] print '* starting:', ' '.join(cmdargs) pid = os.spawnv(os.P_NOWAIT, cmdargs[0], cmdargs) try: time.sleep(1) # hack - wait a bit to make sure the server is up os.environ['GRAPHSERVER'] = '%s:%d' % (host, port) try: test_display_dot_file() finally: del os.environ['GRAPHSERVER'] finally: os.kill(pid, signal.SIGTERM)
def execute(self, testdir=None, iterations=10000): if not testdir: testdir = self.tmpdir os.chdir(testdir) file = os.path.join(testdir, 'foo') # Want to use 3/4 of all memory for each of # bash-shared-mapping and usemem kilobytes = (3 * utils_memory.memtotal()) / 4 # Want two usemem -m megabytes in parallel in background. pid = [None, None] usemem = os.path.join(self.srcdir, 'usemem') args = ('usemem', '-N', '-m', '%d' % (kilobytes / 1024)) # print_to_tty ('2 x ' + ' '.join(args)) for i in (0, 1): pid[i] = os.spawnv(os.P_NOWAIT, usemem, args) cmd = "%s/bash-shared-mapping %s %d -t %d -n %d" % \ (self.srcdir, file, kilobytes, utils.count_cpus(), iterations) os.system(cmd) for i in (0, 1): os.kill(pid[i], signal.SIGKILL)
def OnItemActivated(self, event): # Open the relevant file at the appropriate line number for editing. self.currentItem = event.m_itemIndex # only call editor if we have both a file and a line number - skip # "Nothing scheduled" lines in the event list. if self.data[self.currentItem][3]: rephash['f'] = self.data[self.currentItem][4] rephash['n'] = self.data[self.currentItem][5] if editor == '': changed = False dlg = wxRemEditor.EditWindow(rephash['f'], rephash['n']) changed = dlg.ShowModal() dlg.Destroy() if changed: self.Refresh() else: editlist = (editold % rephash).split() retval = os.spawnv(os.P_WAIT, editor, editlist) if retval > 0: self.infoMessage( 'Attempt to start editor %s failed. Check setting in ~/.wxremindrc.' \ % editor, 'Error') else: self.Refresh()
def _StartProcess(self): if self._IsRunning(): return self.currentCount += 1 # OS X can get very unstable during testing. This will hopefully # allow for longer fuzzing runs by killing off some processes # that seem to get "stuck" if self.currentCount % self.restartFinger == 0: os.system('killall -KILL Finder') os.system('killall -KILL Dock') os.system('killall -KILL SystemUIServer') # If no command is specified, assume we are running # exc_handler some other way. if self.Command == None: return args = [] args.append(self.Command) splitArgs = self.Arguments.split(" ") for i in range(len(splitArgs)): if i > 0 and splitArgs[i - 1][-1] == '\\': args[-1] = args[-1][:-1] + " " + splitArgs[i] else: args.append(splitArgs[i]) print "osx.Process._StartProcess():", args self.pid = os.spawnv(os.P_NOWAIT, self.Command, args) time.sleep(1.5) print "osx.Process: pid:", self.pid