def do_start(self, arg): self.get_status() if not self.zd_up: args = [ self.options.python, self.options.zdrun, ] args += self._get_override("-S", "schemafile") args += self._get_override("-C", "configfile") args += self._get_override("-b", "backofflimit") args += self._get_override("-d", "daemon", flag=1) args += self._get_override("-f", "forever", flag=1) args += self._get_override("-s", "sockname") args += self._get_override("-u", "user") if self.options.umask: args += self._get_override("-m", "umask", oct(self.options.umask)) args += self._get_override( "-x", "exitcodes", ",".join(map(str, self.options.exitcodes))) args += self._get_override("-z", "directory") args.extend(self.options.program) if self.options.daemon: flag = os.P_NOWAIT else: flag = os.P_WAIT os.spawnvp(flag, args[0], args) elif not self.zd_pid: self.send_action("start") else: print "daemon process already running; pid=%d" % self.zd_pid return self.awhile(lambda: self.zd_pid, "daemon process started, pid=%(zd_pid)d")
def kill_process(self, node_number, pid): """ """ command = 'ssh node%s kill -term %s'%(node_number, pid) wl = ['sh', '-c', command] os.spawnvp(os.P_WAIT, 'sh', wl) print "process %s on node %s killed"%(pid, node_number)
def EquationProcess(v0, outdir): v = EquationTemplate % v0 ref = sha.new(v).hexdigest() fn = os.path.join(outdir, ref + ".png") if not os.path.exists(fn): print "# Formatting equation %s\n#\t%s" % (ref, repr(v0)[:70]) d = tempfile.mkdtemp() od = os.getcwd() ft = os.path.join(d, "eqn.tex") fd = os.path.join(d, "eqn.dvi") fp = os.path.join(d, "eqn1.png") open(ft, "w").write(v) os.chdir(d) try: res = os.spawnvp(os.P_WAIT, 'latex', [ 'latex', '-interaction', 'batchmode', ft]) if res: raise RuntimeError, "latex failed (%d)" % res res = os.spawnvp(os.P_WAIT, 'dvipng', [ 'dvipng', '-D', '115', '-T', 'tight', '-bg', 'Transparent', fd]) if res: raise RuntimeError, "dvipng failed (%d)" % res finally: os.chdir(od) shutil.copy(fp, fn) shutil.rmtree(d) w, h = getoutput(['identify', '-format', '%w %h', fn]).split() return ref, w, h
def generate_link_stub(links): path=os.path.join(SVMCORBA_RECORD.work_path, 'linkstub') try: os.mkdir(path) except: 1 SVMCORBA_RECORD.stub_path=path for lk in links.keys(): path=os.path.join(SVMCORBA_RECORD.stub_path, links[lk][0]) try: os.mkdir(path) except: 1 p=os.path.join(path, links[lk][1]) try: os.mkdir(p) except: 1 idl_file=os.path.join(p, '%s_%d_link.idl' % (SVMCORBA_RECORD.module_name, SVMCORBA_RECORD.module_num)) if not idl_file in SVMCORBA_RECORD.stub_generated: SVMCORBA_RECORD.stub_generated.append(idl_file) idl=links[lk][2] idlf=open(idl_file, 'w') idlf.write(idl) idlf.close() os.spawnvp(os.P_WAIT, 'fnidl', ['fnidl', idl_file, '--directory='+p])
def submit(self): no_of_files = len(self.f_list) files_per_job = int( math.ceil(no_of_files/float(self.no_of_jobs)) ) for i in range(self.no_of_jobs): job_fname = os.path.join(self.jobdir, 'graph_construct_'+repr(self.initnum+i)+'.sh') out_block = '#!/bin/sh\n' #this is '=' not '+=' tmpdir = os.path.join(self.dir, 'tmp%d'%i) os.mkdir(tmpdir) for j in range(files_per_job): #move files to tmpdir index = i*files_per_job + j if index >= no_of_files: break src = os.path.join(self.dir, self.f_list[index]) dst = os.path.join(tmpdir, self.f_list[index]) os.rename(src, dst) out_block += '~/script/annot/bin/batch_graph_cc.py %s %s\n'%(tmpdir, self.dstdir) job_f = open(job_fname, 'w') job_f.write(out_block) job_f.close() wl = ['qsub', job_fname] os.spawnvp(os.P_WAIT, 'qsub', wl) if index == no_of_files: #there're no files left to allocate. #otherwise, you will submit 'empty' jobs break
def run(self): iter = mcl_input_iterator(self.inf) for mcl_input_block in iter: out_block = mcl_input_block.readline() mclinf = open(self.mclinput_fname, 'w') mclinf.write(mcl_input_block.read()) mclinf.close() parameter = self.parameter.split() wl = ['mcl', self.mclinput_fname, '-o',self.mcloutput_fname] + parameter try: os.spawnvp(os.P_WAIT, 'mcl', wl) except: sys.stderr.write('MCL running error.\n') os.remove(self.mclinput_fname) if os.isfile(self.mcloutput_fname): os.remove(self.mcloutput_fname) sys.exit(1) out_block += '(parameter %s )\n'%self.parameter mcloutf = open(self.mcloutput_fname, 'r') out_block += mcloutf.read() mcloutf.close() self.outf.write(out_block) os.remove(self.mclinput_fname) os.remove(self.mcloutput_fname)
def audioencode(var): # This function uses variables from the outside scope to command it. normcopy(var) oggenc = [ "oggenc", "-q" + str(var["oggquality"]), "-t", var["tracktitle"], "--quiet", "-o" + var["audiofname"], "tmp.audio.pipe.wav", ] mplayer = [ "mplayer", var["fname"], "-hardframedrop", "-vc", "null", "-vo", "null", "-ao", "pcm:file=tmp.audio.pipe.wav:fast", ] os.spawnvp(os.P_NOWAIT, "oggenc", oggenc) os.spawnvp(os.P_WAIT, "mplayer", mplayer)
def sync(self): new=os.path.join(self.root, self.host, "new") current=os.path.join(self.root, self.host, "current") if self.debug: print "running rsync on host", self.host try: if self.conf['map-uid']: ret_val=os.spawnvpe(os.P_WAIT, "rsync", ["rsync", "--archive", "--delete", "--numeric-ids", "--hard-links", "--sparse", "--link-dest="+current, self.host+"::backup/", new], { "USER": self.user, "RSYNC_PASSWORD": self.password } ) else: ret_val=os.spawnvpe(os.P_WAIT, "rsync", ["rsync", "-rlptD", "--delete", "--hard-links", "--sparse", "--link-dest="+current, self.host+"::backup/", new], { "USER": self.user, "RSYNC_PASSWORD": self.password } ) except: ret_val=1 if ret_val > 0: print "cleanup" os.spawnvp(os.P_WAIT, "rm", ["rm", "-r", new]) print self.host,"failed" return stime=time.time() dirbase='/'.join([str(de).zfill(2) for de in time.localtime(stime)[0:3]]) dir=':'.join([str(de).zfill(2) for de in time.localtime(stime)[3:6]]) try: os.makedirs(os.path.join(self.root, self.host, dirbase)) except OSError, oe: if oe.errno != 17: raise
def run_l2_binary(binary_filename, stdout_filename, stderr_filename, parallel_prefix=None, verbose=False): l2_command = "%s %s > %s 2> %s" % (TIME_COMMAND, binary_filename, stdout_filename, stderr_filename) if parallel_prefix != None: run_command = ["/bin/sh", "-c", "%s %s" % (parallel_prefix, l2_command)] else: run_command = ["/bin/sh", "-c", l2_command] if verbose: print "Running command: %s" % " ".join(run_command) os.spawnvp(os.P_WAIT, run_command[0], run_command) stderr_fo = open(stderr_filename, "r") # Once done check stderr for errors stderr_contents = [] run_error = False for stderr_line in stderr_fo.readlines(): for check_string in ERROR_CHECK_STRINGS: if stderr_line.find(check_string) >= 0: run_error = True stderr_contents.append(stderr_line) stderr_fo.close() # Output stderr if verbose and an error was found if run_error and verbose: print >> sys.stderr, "ERROR detected in run of %s" % binary_filename for stderr_line in stderr_contents: print >> sys.stderr, LOG_VERBOSE_PREFIX, stderr_line,
def buildDMG(self): # Remove DMG if it already exists if os.path.exists(self.dmgName): os.unlink(self.dmgName) createargs = [ 'hdiutil', 'create', '-fs', 'HFSX', '-format', 'UDZO', self.dmgName, '-imagekey', 'zlib-level=9', '-srcfolder', self.bundleDir, '-volname', self.volume_label ] if self.applications_shortcut: scriptargs = [ 'osascript', '-e', 'tell application "Finder" to make alias \ file to POSIX file "/Applications" at POSIX file "%s"' % os.path.realpath(self.buildDir) ] if os.spawnvp(os.P_WAIT, 'osascript', scriptargs) != 0: raise OSError('creation of Applications shortcut failed') createargs.append('-srcfolder') createargs.append(self.buildDir + '/Applications') # Create the dmg if os.spawnvp(os.P_WAIT, 'hdiutil', createargs) != 0: raise OSError('creation of the dmg failed')
def main(): templates = read_config() if X_SELECTION: input = get_x_selection() else: input = sys.stdin.read() input = input.strip() log('Read input "%s"' % input) for (template, cmd) in templates.items(): match = re.search(template, input) if match: log('Matched template "%s" with command "%s"' % (template, cmd)) cmd = match.expand(cmd).split() cmd_string = ' '.join(cmd) log('Expanded command to "%s"' % cmd_string) if TEST: print cmd_string else: os.spawnvp(os.P_NOWAIT, cmd[0], cmd) sys.exit(0) log('No matching template found.', error=True) sys.exit(1)
def _plot(self, gridFile, solutionFile=None, aggregatesFile=None, connectionsFile=None): config = DOUGConfigParser(name='Plot parameters') config.addConfig(self.app.config) configPanel = ConfigPanel(self.app.root, config, title="Plot configuration", sectionNames=['gridplot']) if not configPanel.done: return LOG.info("Show plot of %s", gridFile) gridplot=os.path.join(os.path.dirname(sys.argv[0]), 'gridplot.py') args = [gridplot, gridplot] args.extend(['--gin', gridFile]) if solutionFile: args.extend(['--sin', solutionFile]) if aggregatesFile: args.extend(['--ain', aggregatesFile]) if connectionsFile: args.extend(['--cin', connectionsFile]) plargs=[] device=config.get('gridplot', 'device') plargs.extend(['-dev', device]) aggr=config.get('gridplot', 'aggr', None) if aggr: args.extend(['--aggr', aggr]) args.extend(['--plplot', " ".join(plargs)]) LOG.debug("Spawn '%s'", args) os.spawnvp(os.P_NOWAIT, 'python', args)
def make_pngs_into_an_avi(fps): video_command = ('mencoder', 'mf://*.png', '-mf', 'type=png:w=800:h=600:fps='+str(fps), '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4', '-oac', 'copy', '-o', 'output.avi') os.spawnvp(os.P_WAIT, 'mencoder', video_command) print "The movie was drawn to 'output.avi'" audio_command = ('mencoder', '-ovc', 'copy', '-audiofile', 'fast_fourier_music.wav', '-oac', 'copy', 'output.avi', '-o', 'video_new.avi') os.spawnvp(os.P_WAIT, 'mencoder', audio_command) # os.system(mencoder -ovc copy -audiofile drumChordSort.wav -oac copy output.avi -o video_new.avi") return
def generateASTXML(self, target, context): dialog=NewASTXMLDialog() if dialog.run()>0: dirpath = dialog.directoryName xmlFilename = dialog.xmlFilename fortranFiles = list(dialog.filenames) if not xmlFilename: xmlFilename="%s.xml" % fortranFiles[0] relFortranFiles = [] for name in fortranFiles: if name.startswith(dirpath): name = name[len(dirpath):] if name[0]==os.path.sep: name = name[1:] relFortranFiles.append(name) dirnames = list(dialog.dirnames) commandLine = ['java', '-Xmx512M', '-jar', 'parser/ofp/FortranCPR.jar', '-X', os.path.join(dirpath,xmlFilename), '-O', dirpath, '-I', dirpath] if dirnames: commandLine.append("-P") commandLine.append(",".join(dirnames)) commandLine.extend(relFortranFiles) LOG.info("Running %s", " ".join(commandLine)) os.spawnvp(os.P_WAIT, 'java', commandLine)
def edit_config_file(): if os.path.isfile(_SETTINGS_FILE) != True: os.mknod(_SETTINGS_FILE) show_help_dlg("<b>No <i>.sshplus</i> config file found, we created one for you!\n\nPlease edit the file and reload the config.</b>\n\n%s" % \ _EDIT_CONFIG, error=True) os.spawnvp(os.P_NOWAIT, 'xdg-open', ['xdg-open', _SETTINGS_FILE]) os.wait3(os.WNOHANG)
def sa_learn(type, user, mailarray): """Call sa-learn for mailarray and learn them as typ in user's db""" for part in range(0,len(mailarray),50): os.spawnvp(os.P_WAIT, "sa-learn", ["sa-learn", "-u "+user, "--dbpath="+os.path.join("/mail", user, ".spamassassin"), \ "--"+type, "--no-sync"]+mailarray[part:part+50]) #print "sa-learn", ["sa-learn", "-u "+user, "--dbpath="+os.path.join("/mail", user, ".spamassassin"), "--"+type, "--no-sync"]+mailarray[part:part+50] os.spawnvp(os.P_WAIT, "sa-learn", ["sa-learn", "-u "+user, "--dbpath="+os.path.join("/mail", user, ".spamassassin"), "--sync"])
def exec_storm_class(klass, jvmtype="-server", jvmopts=[], extrajars=[], args=[], fork=False, daemon=True, daemonName=""): global CONFFILE storm_log_dir = confvalue("storm.log.dir",[CLUSTER_CONF_DIR]) if(storm_log_dir == None or storm_log_dir == "null"): storm_log_dir = os.path.join(STORM_DIR, "logs") all_args = [ JAVA_CMD, jvmtype, "-Ddaemon.name=" + daemonName, get_config_opts(), "-Dstorm.home=" + STORM_DIR, "-Dstorm.log.dir=" + storm_log_dir, "-Djava.library.path=" + confvalue("java.library.path", extrajars, daemon), "-Dstorm.conf.file=" + CONFFILE, "-cp", get_classpath(extrajars, daemon), ] + jvmopts + [klass] + list(args) print("Running: " + " ".join(all_args)) if fork: os.spawnvp(os.P_WAIT, JAVA_CMD, all_args) elif is_windows(): # handling whitespaces in JAVA_CMD try: ret = sub.check_output(all_args, stderr=sub.STDOUT) print(ret) except sub.CalledProcessor as e: sys.exit(e.returncode) else: os.execvp(JAVA_CMD, all_args) os._exit()
def __generate_movie__(movie_specification): """ function generate a movie using mencoder based on frame's files extension or a file listing """ m = movie_specification if m.idx == None: output_file = as_path(m.directory, '%s.avi' % (m.name)) else: output_file = as_path(m.directory, '%s_part_%02i.avi' % (m.name, m.idx)) #frames_file if not null contains frames listing frames_source = 'mf://' + (('@' + m.frames_file) if m.frames_file else as_path(m.movie_directory, m.movie_frames)) command = ('mencoder', frames_source, #'mf://@' + m.frames_file, '-mf', #'type=png:w=1024:h=800:fps=30', 'type=png:w=' + str(m.width) + \ ':h=' + str(m.height) + \ ':fps=' + str(m.fps), '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4:mbd=2:trell', '-oac', 'copy', '-o', '%s' % (output_file)) os.spawnvp(os.P_WAIT, 'mencoder', command) return output_file
def start_servers(): print("==> Starting servers", flush=True) print(" -> Gitolite Log Tail", flush=True) gitolite_log_fifo = "/tmp/gitolite_logs.fifo" if not os.path.exists(gitolite_log_fifo): os.mkfifo(gitolite_log_fifo) os.makedirs(".ssh/", mode=0o700, exist_ok=True) with open(".ssh/environment", "w") as f: f.write("GL_LOGFILE={gitolite_log_fifo}\n".format(**locals())) # SSHD doesn't pass its environment on to gitolite, so the critical # nss-wrapper stuff doesn't get through. Fix this. for k,v in os.environ.items(): f.write("{k}={v}\n".format(**locals())) tail_cmd = ["tail", "-f", gitolite_log_fifo] tail_pid = os.spawnvp(os.P_NOWAIT, tail_cmd[0], tail_cmd) print(" -> SSHD", flush=True) sshd_cmd = ["/sbin/sshd", "-f", "./sshd_config", "-D", "-e"] sshd_pid = os.spawnvp(os.P_NOWAIT, sshd_cmd[0], sshd_cmd) print(" -> Apache HTTPD", flush=True) httpd_cmd = ["httpd", "-d", ".", "-f", "httpd.conf", "-DFOREGROUND"] httpd_pid = os.spawnvp(os.P_NOWAIT, httpd_cmd[0], httpd_cmd) return set((sshd_pid, httpd_pid))
def OnOpenDirectory(self, widget): downloaddir = self.frame.np.config.sections["transfers"]["downloaddir"] incompletedir = self.frame.np.config.sections["transfers"]["incompletedir"] if incompletedir == "": incompletedir = downloaddir filemanager_config = self.frame.np.config.sections["ui"]["filemanager"] transfer = self.selected_transfers[0] filemanager = filemanager_config.split()[0] filemanager_args = filemanager_config.split(filemanager)[1] arg = filemanager_args.split('$')[0].strip() complete_path = os.path.join(downloaddir, transfer.path) arg_list = [] arg_list.append(filemanager) for i in arg.split(): arg_list.append(i) if transfer.path is "": if transfer.status is "Finished": arg_list.append(downloaddir) else: arg_list.append(incompletedir) elif os.path.exists(complete_path): # and tranfer.status is "Finished" arg_list.append(complete_path) else: arg_list.append(incompletedir) #os.system("%s %s &") os.spawnvp(os.P_WAIT, filemanager, arg_list)
def die(ret, str=None): "Print error and exit with errorcode" global convertor, oopid if str: error(0, 'Error: %s' % str) ### Did we start an instance ? if oopid: ### If there is a GUI now attached to the instance, disable listener if convertor.desktop.getCurrentFrame(): for bin in ('soffice.bin', 'soffice', ): try: os.spawnvp(os.P_NOWAIT, bin, [bin, "-headless", "-nologo", "-nodefault", "-norestore", "-nofirststartwizard", "-unaccept=%s" % op.connection]); error(2, 'OpenOffice listener successfully disabled.') break except Exception, e: error(3, "Launch of %s failed.\n%s" % (bin, e)) continue ### If there is no GUI attached to the instance, terminate instance else: try: convertor.desktop.terminate() except DisposedException: error(2, 'OpenOffice instance successfully terminated.')
def exec_storm_class( klass, jvmtype="-server", jvmopts=[], extrajars=[], args=[], fork=False, daemon=True, daemonName="" ): global CONFFILE storm_log_dir = confvalue("storm.log.dir", [CLUSTER_CONF_DIR]) if storm_log_dir == None or storm_log_dir == "nil": storm_log_dir = os.path.join(STORM_DIR, "logs") all_args = ( [ JAVA_CMD, jvmtype, "-Ddaemon.name=" + daemonName, get_config_opts(), "-Dstorm.home=" + STORM_DIR, "-Dstorm.log.dir=" + storm_log_dir, "-Djava.library.path=" + confvalue("java.library.path", extrajars, daemon), "-Dstorm.conf.file=" + CONFFILE, "-cp", get_classpath(extrajars, daemon), ] + jvmopts + [klass] + list(args) ) print ("Running: " + " ".join(all_args)) if fork: os.spawnvp(os.P_WAIT, JAVA_CMD, all_args) elif is_windows(): # handling whitespaces in JAVA_CMD sub.call(all_args) else: os.execvp(JAVA_CMD, all_args)
def MouseDo(cmdstring, debug=False): if debug: logger.debug(cmdstring) if windows: subprocess.call(["java", "-cp", os.environ["JAVA"], "RemoteControlRobot"] + cmdstring.split(' ')) else: os.spawnvp(os.P_WAIT, 'java', ["java", "-cp", os.environ["JAVA"], "RemoteControlRobot"] + cmdstring.split(' '))
def diff(dumpa=None, dumpb=None, eol='\n'): """ use /usr/bin/diff or alternative in PYFUSION_DIFF to show the differences adding a config file made. With no args, the last two differences are shown. Otherwise args must be history dict entries (not just keys) e.g. pyfusion.conf.utils.diff(pyfusion.conf.history[0],pyfusion.conf.history[1]) key gives the read sequence of files - this would be lost in a dictionary key = 0 is the first read """ if dumpa is None: pf_hist = pyfusion.conf.history seq = sort(pf_hist.keys()) oldest_to_be_printed = max(1,len(seq)-2) for s in seq[oldest_to_be_printed:]: diff(pf_hist[seq[s-1]], pf_hist[seq[s]],eol=eol) return import os if dumpa[0].find(eol): eol='' # don;t set eol if we already have it fa = '/tmp/filea' fb = '/tmp/fileb' filea = open(fa,'w') filea.writelines([lin+eol for lin in dumpa]) filea.close() fileb = open(fb,'w') fileb.writelines([lin+eol for lin in dumpb]) fileb.close() diffprog = os.getenv('PYFUSION_DIFF','/usr/bin/diff') # P_WAIT is best for emacs diff, as you see the differences in order os.spawnvp(os.P_WAIT,diffprog,[diffprog,fa, fb])
def createMovie(self): ''' open all movie-template-*.png's and create a movie out of it ''' print "createMovie(): writing image data" frameSizeImage = read_png(''.join([self.templateMovDataDirectory,'/.screenShot',str(0),'.png'])) frameSize = (np.shape(frameSizeImage)[1],np.shape(frameSizeImage)[0]) try: FFMpegWriter = animation.writers['mencoder'] except: print "ERROR: Visualisation3D.createMovie(): mencoder libary is not installed, could not create movie!"; return try: fileName = ''.join([self.movieSaveDirectory,'/',self.networkName,'_',str(self.movieNumber),self.movieFileType]) imageName = ''.join(['mf://',self.templateMovDataDirectory,'/.screenShot%d.png']) imageType = ''.join(['type=png:w=',str(frameSize[0]),':h=',str(frameSize[1]),':fps=24']) command = ('mencoder', imageName, '-mf', imageType, '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4', '-oac', 'copy', '-o', fileName) os.spawnvp(os.P_WAIT, 'mencoder', command) self.movieNumber = self.movieNumber+1 print "createMovie(): created movie sucessfull" except: print "ERROR: Visualisation3D.createMovie(): mencoder libary is not installed, could not create movie!"; return
def EquationProcess(v0, outdir): v = EquationTemplate % v0 ref = sha.new(v).hexdigest() tfn = os.path.join(outdir, "tmp_%s" % os.getpid() + ref + ".png") fn = os.path.join(outdir, ref + ".png") if not os.path.exists(fn): print "# Formatting equation %s\n#\t%s" % (ref, repr(v0)[:70]) d = tempfile.mkdtemp() od = os.getcwd() ft = os.path.join(d, "eqn.tex") fd = os.path.join(d, "eqn.dvi") fp = os.path.join(d, "eqn1.png") open(ft, "w").write(v) os.chdir(d) try: res = os.spawnvp(os.P_WAIT, "latex", ["latex", "-interaction", "batchmode", ft]) if res: raise RuntimeError, "latex failed (%d)" % res res = os.spawnvp(os.P_WAIT, "dvipng", ["dvipng", "-D", "115", "-T", "tight", "-bg", "Transparent", fd]) if res: raise RuntimeError, "dvipng failed (%d)" % res finally: os.chdir(od) shutil.copy(fp, tfn) os.rename(tfn, fn) shutil.rmtree(d) w, h = getoutput(["identify", "-format", "%w %h", fn]).split() return ref, w, h
def OnInstallButtonClicked(self, widget): TimeInit = time.time() self.CheckButtonClear(0) if (len(sys.argv) < 3 or self.install_flag) and not self.undefined_error_flag: self.InfoCache = InfoCache(self) self.loadcache_flag = False if not self.InfoCache.Installed or self.InfoCache.source_package or self.InfoCache.new_package != 0: package_filename = self.package_filename.replace(' ', '\ ') if self.InfoCache.new_package != -1: command = ['/usr/bin/gurpmi2', package_filename, FLAGFILE] else: command = ['rpm', '-U', '--oldpackage', package_filename, FLAGFILE] ID = commands.getoutput('id -u') if ID != '0': command.insert(0, './findsu') command.insert(0, './shcomm.py') os.spawnvp(os.P_NOWAIT, command[0], command) if self.InfoCache.Name == 'refresher': self.ChangeWindow(self.wizard2_window, self.wizard3_window) else: WaitProc() if self.InfoCache.source_package != True or self.InfoCache.new_package != 0: try: Inst = IntVersion(get_rpm_unerrored_output('rpm -q --queryformat \"%{Version}\" ' + self.InfoCache.Name)) Pack = IntVersion(self.InfoCache.Version) Rel = get_rpm_unerrored_output('rpm -q --queryformat \"%{Release}\" ' + self.InfoCache.Name) if Inst == Pack and Rel == self.InfoCache.Release: self.ChangeWindow(self.wizard2_window, self.wizard3_window) else: deps = self.DependencyFind() if deps != '': self.desc.set_markup(_('<b><big>Failed dependencies:</big></b>\n\n') + deps) self.glade_xml_wizard2_window.get_widget("label159").set_text(_("Force")) self.force_install_mode_flag = True self.uninstall_button.set_sensitive(True) self.install_button.set_sensitive(False) else: self.desc.set_markup(_('<b><big>Undefined error</big>\n\n If you\'re versed user, press Details button for details!\n(It\'s where the Install button used to be.)</b>')) self.glade_xml_wizard2_window.get_widget("label159").set_text(_("Force")) self.force_install_mode_flag = True self.uninstall_button.set_sensitive(True) self.undefined_error_flag = Trueq self.glade_xml_wizard2_window.get_widget("label43").set_text(_("Details")) self.error_log = 'error 1' except: self.desc.set_markup(_('<b><big>Undefined error</big>\n\n If you\'re versed user, press Details button for details!\n(It\'s where the Install button used to be.)</b>')) self.undefined_error_flag = True self.glade_xml_wizard2_window.get_widget("label43").set_text(_("Details")) self.error_log = 'error 2' else: self.ChangeWindow(self.wizard2_window, self.wizard3_window) elif self.undefined_error_flag: self.install_button.set_sensitive(False) self.desc.set_markup(SlitText(self.error_log)) else: command = '/usr/bin/gurpmi2 ' + self.package_filename err = commands.getoutput(command) self.ChangeWindow(self.wizard2_window, self.wizard3_window) print 'OnInstallButtonClicked(): ', time.time() - TimeInit
def start_websocket_server(): """Start the websocket server.""" os.chdir('server') if os.name == 'posix': os.spawnvp(os.P_NOWAIT, "python2", ["python2", "serve.py"]) else: os.spawnv(os.P_NOWAIT, "C:\\Python27\\python.exe", ["python.exe", "serve.py"])
def postInstall(): try: os.makedirs("/var/run/hald") except OSError: pass os.spawnvp(os.P_NOWAIT, "/usr/bin/chown", ["/usr/bin/chown", "haldaemon:haldaemon", "/var/run/hald"]) os.system("/sbin/rc-update add hald default") os.system("/sbin/depscan.sh")
def postgui(self): postgui_halfile = INFO.POSTGUI_HALFILE_PATH log.info("postgui filename: yellow<{}>".format(postgui_halfile)) if postgui_halfile: if postgui_halfile.lower().endswith('.tcl'): res = os.spawnvp(os.P_WAIT, "haltcl", ["haltcl", "-i",self.inipath, postgui_halfile]) else: res = os.spawnvp(os.P_WAIT, "halcmd", ["halcmd", "-i",self.inipath,"-f", postgui_halfile]) if res: raise SystemExit, res
def xargs(frame_names, command_list): temp_files = [] rc = 0 try: # Fetch the contents of each frame and put them in tmp files. for frame_name in frame_names: rc, next_temp_file = readFrameToTempFile(frame_name) temp_files.append(next_temp_file) if rc != 0: break else: # Build the complete command and args. args = command_list[:] for temp_file in temp_files: args.append(temp_file.name) os.spawnvp(os.P_WAIT, args[0], [os.path.basename(args[0])] + args[1:]) finally: # Clean up any temp files. for temp_file in temp_files: os.unlink(temp_file.name) return rc
def start(): """Ensure WM is running.""" global wm_pid assert wm_pid is None unused, wm_command = get_window_manager() if wm_command: wm_pid = os.spawnvp(os.P_NOWAIT, wm_command[0], wm_command) children.register_child(wm_pid, wm_died) info("Started window manager; PID %s", wm_pid) import session session.may_run_login_script() else: choose_wm('None of the default window managers are installed')
def c_link_list(obj_files, verbose_flag = 0, cplus = 0): # Link the given object files into a dynamically # loadable extension file. Returns the pathname # of the resulting file. os.environ["MACOSX_DEPLOYMENT_TARGET"] = "10.3" out_file = replace_suffix(obj_files[0], ".so") linker = linkers[bool(cplus)] args = [linker] + linker_options + obj_files + ["-o", out_file] if verbose_flag or verbose: print " ".join(args) status = os.spawnvp(os.P_WAIT, linker, args) if status <> 0: raise CCompilerError("Linker returned status %s" % status) return out_file
def Exec(self, argv): cwd = os.getcwd() t, relpath = self.WhichTier(cwd) assert t >= 0, 'Not in any tier: %s' % relpath mret = 0 for t in range(len(self.tiers)): path = self.InTier(t, relpath) print('====== in', path.rstrip('/')) os.chdir(path) ret = os.spawnvp(os.P_WAIT, argv[0], argv) if ret: print('====== returned', ret) mret = max(mret, ret) return mret
def run(self): """ Command execution. """ self.run_command('build') build = self.get_finalized_command('build') self.bundleDir = os.path.join(build.build_base, self.bundle_name + ".app") self.contentsDir = os.path.join(self.bundleDir, 'Contents') self.resourcesDir = os.path.join(self.contentsDir, 'Resources') self.binDir = os.path.join(self.contentsDir, 'MacOS') self.frameworksDir = os.path.join(self.contentsDir, 'Frameworks') executable = self.distribution.executables[0].targetName _, self.bundle_executable = os.path.split(executable) self.mkpath(self.resourcesDir) self.mkpath(self.binDir) self.mkpath(self.frameworksDir) self.copy_tree(DIST_PATH, self.binDir) if self.iconfile: self.copy_file(self.iconfile, os.path.join(self.resourcesDir, 'icon.icns')) for framework in self.include_frameworks: self.copy_tree(framework, os.path.join(self.frameworksDir, os.path.basename(framework))) self.execute(self.create_plist, ()) self.execute(self.setRelativeReferencePaths, ()) self.execute(self.prepare_qt_app, ()) if self.codesign_identity: signargs = ['codesign', '-s', self.codesign_identity] if self.codesign_entitlements: signargs.append('--entitlements') signargs.append(self.codesign_entitlements) if self.codesign_deep: signargs.insert(1, '--deep') if self.codesign_resource_rules: signargs.insert(1, '--resource-rules=' + self.codesign_resource_rules) signargs.append(self.bundleDir) if os.spawnvp(os.P_WAIT, 'codesign', signargs) != 0: raise OSError('Code signing of app bundle failed')
def main(args): import_envvars(False, False) export_envvars() if args.enable_insecure_key: install_insecure_key() if not args.skip_startup_files: run_startup_files() runit_exited = False exit_code = None if not args.skip_runit: runit_pid = start_runit() try: exit_status = None if len(args.main_command) == 0: runit_exited, exit_code = wait_for_runit_or_interrupt(runit_pid) if runit_exited: if exit_code is None: info("Runit exited with unknown status") exit_status = 1 else: exit_status = os.WEXITSTATUS(exit_code) info("Runit exited with status %d" % exit_status) else: info("Running %s..." % " ".join(args.main_command)) pid = os.spawnvp(os.P_NOWAIT, args.main_command[0], args.main_command) try: exit_code = waitpid_reap_other_children(pid) if exit_code is None: info("%s exited with unknown status." % args.main_command[0]) exit_status = 1 else: exit_status = os.WEXITSTATUS(exit_code) info("%s exited with status %d." % (args.main_command[0], exit_status)) except KeyboardInterrupt: stop_child_process(args.main_command[0], pid) except BaseException as s: warn("An error occurred. Aborting.") stop_child_process(args.main_command[0], pid) raise sys.exit(exit_status) finally: if not args.skip_runit: shutdown_runit_services() if not runit_exited: stop_child_process("runit daemon", runit_pid) wait_for_runit_services()
def launch_application(opts, config): qtpyvcp.OPTIONS.update(opts) qtpyvcp.CONFIG.update(config) hal_comp = hal.component('qtpyvcp') LOG.debug('Loading data plugings') loadPlugins(config['data_plugins']) log_time('done loading data plugins') LOG.debug('Initializing app') app = _initialize_object_from_dict(config['application']) log_time('done initializing app') LOG.debug('Loading dialogs') loadDialogs(config['dialogs']) log_time('done loading dialogs') LOG.debug('Loading windows') loadWindows(config['windows']) log_time('done loading windows') LOG.debug('Initializing widgets') app.initialiseWidgets() log_time('done initializing widgets') hal_comp.ready() # load any post GUI hal file postgui_halfile = INFO.getPostguiHalfile() if postgui_halfile is not "": if not os.path.exists(postgui_halfile): raise IOError('The specified POSTGUI_HALFILE does not exist: %s' % postgui_halfile) ini_path = INFO.INI_FILE LOG.info('Loading POSTGUI_HALFILE: %s', postgui_halfile) res = os.spawnvp(os.P_WAIT, "halcmd", ["halcmd", "-i", ini_path, "-f", postgui_halfile]) if res: raise SystemExit("Failed to load POSTGUI_HALFILE with error: %s" % res) # suppress QtQuick warnings app.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings) sys.exit(app.exec_())
def exec_storm_class(klass, jvmtype="-server", jvmopts=[], extrajars=[], args=[], fork=False, daemon=True, daemonName=""): global CONFFILE storm_log_dir = confvalue("storm.log.dir",[CLUSTER_CONF_DIR]) if(storm_log_dir == None or storm_log_dir == "nil"): storm_log_dir = os.path.join(STORM_DIR, "logs") all_args = [ JAVA_CMD, jvmtype, "-Ddaemon.name=" + daemonName, get_config_opts(), "-Dstorm.home=" + STORM_DIR, "-Dstorm.log.dir=" + storm_log_dir, "-Djava.library.path=" + confvalue("java.library.path", extrajars, daemon), "-Dstorm.conf.file=" + CONFFILE, "-cp", get_classpath(extrajars, daemon), ] + jvmopts + [klass] + list(args) print("Running: " + " ".join(all_args)) if fork: os.spawnvp(os.P_WAIT, JAVA_CMD, all_args) elif is_windows(): # handling whitespaces in JAVA_CMD sub.call(all_args) else: os.execvp(JAVA_CMD, all_args)
def umount_all(topdir): "Unmount every mount under topdir" logger = logging.getLogger("koji.build") for path in scan_mounts(topdir): logger.debug('Unmounting %s' % path) cmd = ['umount', '-l', path] rv = os.spawnvp(os.P_WAIT, cmd[0], cmd) if rv != 0: raise koji.GenericError('umount failed (exit code %r) for %s' % (rv, path)) #check mounts again remain = scan_mounts(topdir) if remain: raise koji.GenericError("Unmounting incomplete: %r" % remain)
def graph(self): runDir = self.EVAL_RESULTS + os.sep + self.NAME runName = runDir + os.sep + self.NAME configName = runName+".config" f = open(configName, 'w') f.write("1 %s\n%s.raw\n%s\n%s\n@date"%(runName,runName,runName,runName)) f.close() curDir = os.getcwd() os.chdir(runDir) print "MAKING GRAPH" signal = os.spawnvp(os.P_WAIT, "makeGraph.pl", ["makeGraph.pl", configName]) if signal != 0: print "Recieved error signal from makeGraph.pl: %d"%(signal) os.chdir(curDir)
def term(self, sh="/bin/sh"): """ Open a terminal on a node. :param str sh: shell to open terminal with :return: terminal command result :rtype: int """ args = ("xterm", "-ut", "-title", self.name, "-e", constants.VCMD_BIN, "-c", self.ctrlchnlname, "--", sh) if "SUDO_USER" in os.environ: args = ("su", "-s", "/bin/sh", "-c", "exec " + " ".join(map(lambda x: "'%s'" % x, args)), os.environ["SUDO_USER"]) return os.spawnvp(os.P_NOWAIT, args[0], args)
def do_start(self, arg): self.get_status() if not self.zd_up: if self.options.zdrun: args = [self.options.python, self.options.zdrun] else: args = [self.options.python, sys.argv[0]] os.environ['DAEMON_MANAGER_MODE'] = '1' args += self._get_override("-S", "schemafile") args += self._get_override("-C", "configfile") args += self._get_override("-b", "backofflimit") args += self._get_override("-f", "forever", flag=1) args += self._get_override("-s", "sockname") args += self._get_override("-u", "user") args += self._get_override("-t", "transcript") if self.options.umask: args += self._get_override("-m", "umask", oct(self.options.umask)) args += self._get_override( "-x", "exitcodes", ",".join(map(str, self.options.exitcodes))) args += self._get_override("-z", "directory") args.extend(self.options.program) args.extend(self.options.args[1:]) if self.options.daemon: flag = os.P_NOWAIT else: flag = os.P_WAIT os.spawnvp(flag, args[0], args) elif not self.zd_pid: self.send_action("start") else: print("daemon process already running; pid=%d" % self.zd_pid) return if self.options.daemon: return self.awhile(self._start_cond, "daemon process started, pid=%(zd_pid)d")
def main(): if len(sys.argv[1:]) < 2: sys.stderr.write('%s: at least 2 arguments expected.\n' % sys.argv[0]) sys.exit(1) env.inherit() logs.setup(tty=sys.stderr, parent_logs=env.v.LOG, pretty=env.v.PRETTY, color=env.v.COLOR) target = sys.argv[1] deps = sys.argv[2:] for d in deps: assert d != target me = state.File(name=target) # Build the known dependencies of our primary target. This *does* require # grabbing locks. os.environ['REDO_NO_OOB'] = '1' argv = ['redo-ifchange'] + deps rv = os.spawnvp(os.P_WAIT, argv[0], argv) if rv: sys.exit(rv) # We know our caller already owns the lock on target, so we don't have to # acquire another one; tell redo-ifchange about that. Also, REDO_NO_OOB # persists from up above, because we don't want to do OOB now either. # (Actually it's most important for the primary target, since it's the one # who initiated the OOB in the first place.) os.environ['REDO_UNLOCKED'] = '1' argv = ['redo-ifchange', target] rv = os.spawnvp(os.P_WAIT, argv[0], argv) if rv: sys.exit(rv)
def schedule(self, job): import pyre.util as util # Fix-up the job. if not job.task: job.task = "jobname" job.walltime = util.hms(job.dwalltime.value) job.arguments = ' '.join(job.arguments) # Generate the main SGE batch script. script = self.retrieveTemplate('batch.sh', ['schedulers', 'scripts', self.name]) if script is None: self._error.log("could not locate batch script template for '%s'" % self.name) sys.exit(1) script.scheduler = self script.job = job if self.dry: print script return try: import os, tempfile filename = tempfile.mktemp() s = open(filename, 'w') print >>s, script s.close() cmd = [self.command, filename] self._info.log("spawning: %s" % ' '.join(cmd)) status = os.spawnvp(os.P_WAIT, cmd[0], cmd) os.remove(filename) exitStatus = None if (os.WIFSIGNALED(status)): statusStr = "signal %d" % os.WTERMSIG(status) elif (os.WIFEXITED(status)): exitStatus = os.WEXITSTATUS(status) statusStr = "exit %d" % exitStatus else: statusStr = "status %d" % status self._info.log("%s: %s" % (cmd[0], statusStr)) except IOError, e: self._error.log("%s: %s" % (self.command, e)) return
def run_target(executable): file_name = os.tempnam() return_code = os.spawnvp(os.P_WAIT, executable[0], executable) if (return_code == 0 and os.access('gmon.out', os.F_OK)): os.system('mv gmon.out ' + file_name) else: print 'ERROR:', return_code, 'in executing', executable[0] return None if (os.access(file_name, os.F_OK)): return file_name else: return None
def convert_vtt(filename, force): (fn, fe) = os.path.splitext(filename) nargs = ['ffmpeg'] if force: nargs.append('-y') nargs.append('-i') nargs.append(filename) nargs.append('{}.srt'.format(fn)) sys.stdout.flush() ret = os.spawnvp(os.P_WAIT, nargs[0], nargs) if ret != 0: print('convert fail, exit code: {:d}'.format(ret)) exit(ret)
def hookDebugger(debugger='gdb'): """debugging helper, hooks debugger to running interpreter process """ import os pid = os.spawnvp(os.P_NOWAIT, debugger, [debugger, '-q', 'python', str(os.getpid())]) # give debugger some time to attach to the python process import time time.sleep( 1 ) # verify the process' existence (will raise OSError if failed) os.waitpid( pid, os.WNOHANG ) os.kill( pid, 0 ) return
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 self.timeLimit: proc.extend(["--tmlim", str(self.timeLimit)]) 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 runNaccess(pdb_file,probe=1.4,z_sample=0.05,vdw_file=None,keep_temp=False): """ Wrapper to run naccess. """ curr_dir = os.getcwd() tmp_dir = "%s_sasa-tmp" % pdb_file[:-4] try: os.mkdir(tmp_dir) except OSError as xxx_todo_changeme: (errno,errstr) = xxx_todo_changeme.args if errno == 17: pass else: err = "Problem creating temporary directory (%s)" % tmp_dir raise PdbSasaError(err) shutil.copy(pdb_file,tmp_dir) os.chdir(tmp_dir) # Actually run naccess args = ['naccess',pdb_file,"-p","%.2F" % probe,"-z","%.2F" % z_sample] if vdw_file != None: args.extend(["-r","%s" % vdw_file]) status = os.spawnvp(os.P_WAIT,'naccess',args) if status != 0: err = "Naccess failed with error %i.\n" % status err += "Is naccess in your path?" raise PdbSasaError(err) # Read the .asa file root = pdb_file[:pdb_file.rfind(".")] f = open("%s.asa" % root,'r') lines = f.readlines() f.close() # Grab residue/atom names and calculated accessibility out = ["%s %s\n" % (l[13:26],l[54:62]) for l in lines if l[0:4] == "ATOM"] os.chdir("..") # Remove temporary files if not keep_temp: shutil.rmtree(tmp_dir) return out
def actualSolve(self, lp): """Solve a well formulated lp problem""" if not self.executable(self.path): raise pulp.PulpSolverError("PuLP: cannot execute "+self.path) if not self.keepFiles: pid = os.getpid() tmpLp = os.path.join(self.tmpDir, "%d-pulp.lp" % pid) tmpSol = os.path.join(self.tmpDir, "%d-pulp.sol" % pid) else: tmpLp = lp.name+"-pulp.lp" tmpSol = lp.name+"-pulp.sol" lp.writeLP(tmpLp, writeSOS = 0) #proc = ["scip", "-c", "read \"%s\"" % tmpLp, "-c", "set limits time 180", "-c", "optimize", "-c", "write solution \"%s\"" % tmpSol, "-c", "quit"] proc = ["scip", "-c", "read \"%s\"" % tmpLp] if self.time_limit is not None: proc += ["-c", "set limits time %f"%self.time_limit] if self.ratio_gap is not None: proc += ["-c", "set limits gap %f"%self.ratio_gap] proc += ["-c", "optimize", "-c", "write solution \"%s\"" % tmpSol, "-c", "quit"] proc.extend(self.options) self.solution_time = clock() if not self.msg: proc[0] = self.path pipe = open(os.devnull, 'w') rc = subprocess.call(proc, stdout = pipe, stderr = pipe) if rc: raise pulp.PulpSolverError("PuLP: Error while trying to execute "+self.path) 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 pulp.PulpSolverError("PuLP: Error while trying to execute "+self.path) self.solution_time += clock() if not os.path.exists(tmpSol): raise pulp.PulpSolverError("PuLP: Error while executing "+self.path) lp.status, values = self.readsol(tmpSol) lp.assignVarsVals(values) if not self.keepFiles: try: os.remove(tmpLp) except: pass try: os.remove(tmpSol) except: pass return lp.status
def _spawn_qnx(cmd, search_path=1, verbose=0, dry_run=0): log.info(' '.join(cmd)) if dry_run: return try: if search_path: rc = os.spawnvp(os.P_WAIT, cmd[0], cmd) else: rc = os.spawnv(os.P_WAIT, cmd[0], cmd) except OSError as exc: raise DistutilsExecError("command '%s' failed: %s" % (cmd[0], exc.args[-1])) if rc != 0: msg = "command '%s' failed with exit status %d" % (cmd[0], rc) log.debug(msg) raise DistutilsExecError(msg)
def run_command_killable(*argv): filename = argv[0] status = None pid = os.spawnvp(os.P_NOWAIT, filename, argv) try: status = waitpid_reap_other_children(pid) except BaseException as s: warn("An error occurred. Aborting.") stop_child_process(filename, pid) raise if status != 0: if status is None: error("%s exited with unknown status\n" % filename) else: error("%s failed with status %d\n" % (filename, os.WEXITSTATUS(status))) sys.exit(1)
def buildDMG(self): # Remove DMG if it already exists if os.path.exists(self.dmgName): os.unlink(self.dmgName) # Make dist folder import shutil self.dist_dir = os.path.join(self.buildDir, "dist") if os.path.exists(self.dist_dir): shutil.rmtree(self.dist_dir) self.mkpath(self.dist_dir) # Copy App Bundle dest_dir = os.path.join(self.dist_dir, os.path.basename(self.bundleDir)) self.copy_tree(self.bundleDir, dest_dir) createargs = [ "hdiutil", "create", ] if self.silent: createargs += ["-quiet"] createargs += [ "-fs", "HFSX", "-format", "UDZO", self.dmgName, "-imagekey", "zlib-level=9", "-srcfolder", self.dist_dir, "-volname", self.volume_label, ] if self.applications_shortcut: apps_folder_link = os.path.join(self.dist_dir, "Applications") os.symlink("/Applications", apps_folder_link, target_is_directory=True) # Create the dmg if os.spawnvp(os.P_WAIT, "hdiutil", createargs) != 0: raise OSError("creation of the dmg failed")
def start(self): l="kvm -net nic,model=rtl8139 -net user,hostfwd=tcp:127.0.0.1:10022-:22,hostfwd=tcp:127.0.0.1:18069-:8069,hostfwd=tcp:127.0.0.1:15432-:5432 -drive".split(" ") #l.append('file=%s,if=virtio,index=0,boot=on,snapshot=on'%self.image) l.append('file=%s,snapshot=on'%self.image) #l.extend(['-vnc','127.0.0.1:1']) l.append('-nographic') print " ".join(l) self.pid=os.spawnvp(os.P_NOWAIT, l[0], l) time.sleep(10) signal.alarm(2400) signal.signal(signal.SIGALRM, self.timeout) try: self.run() finally: signal.signal(signal.SIGALRM, signal.SIG_DFL) os.kill(self.pid,15) time.sleep(10)
def start(self): l="kvm -cpu core2duo -smp 2,sockets=2,cores=1,threads=1 -net nic,model=rtl8139 -net user,hostfwd=tcp:127.0.0.1:10022-:22,hostfwd=tcp:127.0.0.1:18069-:8069,hostfwd=tcp:127.0.0.1:15432-:5432 -m 1024 -drive".split(" ") #l.append('file=%s,if=virtio,index=0,boot=on,snapshot=on'%self.image) l.append('file=%s,snapshot=on'%self.image) #l.extend(['-vnc','127.0.0.1:1']) l.append('-nographic') logging.info("Starting kvm: {}".format( " ".join(l))) self.pid=os.spawnvp(os.P_NOWAIT, l[0], l) time.sleep(50) signal.alarm(2400) signal.signal(signal.SIGALRM, self.timeout) try: self.run() finally: signal.signal(signal.SIGALRM, signal.SIG_DFL) os.kill(self.pid,15) time.sleep(10)
def do(self, src, dst): args = [] if self.sudo: args.append('sudo') args.append(self.rsync) if (self.archive): args.append('-a') if (self.compress): args.append('-z') if (self.delete): args.append('--delete') if len(self.options): args.append(self.options) args.append(src) args.append(dst) return os.spawnvp(os.P_WAIT, args[0], args)
def launch(*args): """Runs a program using 0launch, and returns the PID. If 0launch isn't installed, it raises InjectorNotInstalled, telling the user how to get it.""" binpath = os.environ.get('PATH', '').split(':') # Try to run with '0launch' for bindir in binpath: path = os.path.join(bindir, '0launch') if os.path.isfile(path): break else: for x in args: if not x.startswith('-'): raise InjectorNotInstalled(x) raise InjectorNotInstalled(repr(args)) pid = os.spawnvp(os.P_NOWAIT, '0launch', ('0launch', ) + args) return pid
def avconv_conv(path_from, path_to): ext_to = os.path.splitext(path_to)[1] args = ["avconv", "-y", "-i", path_from] if ext_to == ".ogg": args += ["-acodec", "libvorbis"] elif ext_to == ".mp3": args += ["-acodec", "mp3"] elif ext_to == ".mp4": # NOTE: use -strict experimental to allow AAC in avconv # NOTE: resample all to 48000 (96000 is incompatible with AAC) args += ["-acodec", "aac", "-strict", "experimental", "-ar", "48000"] args += [path_to] print(args) return os.spawnvp(os.P_WAIT, "avconv", args)
def c_compile(c_file, verbose_flag=0, cplus=0, obj_suffix=".o"): # Compile the given C source file to produce # an object file. Returns the pathname of the # resulting file. c_file = os.path.join(os.getcwd(), c_file) o_file = replace_suffix(c_file, obj_suffix) include_options = [] for dir in py_include_dirs: include_options.append("-I%s" % dir) compiler = compilers[bool(cplus)] args = [compiler ] + compiler_options + include_options + [c_file, "-o", o_file] if verbose_flag or verbose: print " ".join(args) status = os.spawnvp(os.P_WAIT, compiler, args) if status <> 0: raise CCompilerError("C compiler returned status %s" % status) return o_file
def __run(self, cmd, args=None): """__run: runs cmd using spawnvp. Runs cmd using spawnvp. The shell is avoided so it won't mess up our arguments. If args is very large, the command is run multiple times; args is split xargs style: cmd is passed on each invocation. Unlike xargs, returns immediately if any non-zero return code is received. """ args_l = cmd.split() if args is None: args = [] for i in range(0, len(args) + 1, 100): r = os.spawnvp(os.P_WAIT, args_l[0], args_l + args[i:min(i + 100, len(args))]) if r: return r return 0