def build_command_history(self): cmdlist = self.get_commands() # sys.stderr.write("commd %s\n" % cmdlist) cmd = " ".join(cmdlist) cmd = cmd.strip() prev = os.environ.get(BaseEnv.get_command_info(), "") if prev == "": self.setPath(BaseEnv.get_command_info(), cmd) else: # don't add if the last is the same sprev = prev.split(BaseEnv.commandsep) if len(sprev) > 0: if cmd != sprev[-1].replace("envi ", "").replace(";", ""): # don't add if the last command is the same self.setPath(BaseEnv.get_command_info(), prev + BaseEnv.commandsep + cmd)
def write_bash_history(self): """Export only l'historic store in _BASE_COMMAND """ global cmdout write = None ret = "" if hasattr(cmdout, "info"): write = cmdout.info else: if hasattr(cmdout, "write"): write = cmdout.write ret = "\n" if write is None: comment.error("cannot print this object in echo\n") return key = BaseEnv.get_command_info() if key in self._storeLocalEnv: if len(self._storeLocalEnv[key]) > 0: value = self._storeLocalEnv[key][0] write(MiniEnv._shellFormatSetEnv.format(key, value)) if ret != "": write(ret) return True return False
def execute(self, argv, fromPython=True): """This module is mainly to be used from shell in progress :param argv: a list of envi command :param fromPython: default True. the result of the function is in os.environ :returns bool: True if success """ import subprocess # argument to remove opt = dict() opt["List"] = ["-L", False] opt["Reset"] = ["-Reset", False] # no undo implemented opt["Info"] = ["-h", False] opt["Deamon"] = ['-Deamon', False] opt['Print'] = ["-Print", False] opt['Debug'] = ["-Debug", False] opt['Store'] = ["-Store", False] opt['DictOnly'] = ["-Dodict", False] opt['Clean'] = ["-Clean", False] opt['ExistOnly'] = ["-ExistOnly", False] cmdLines = " ".join(argv[1:]).split("--") if len(cmdLines) > 2: sys.stderr.write("Envi.execute: don't support multiple launch\n") return False cmdLines = [x for x in cmdLines if x != ''] # remove the blank if len(cmdLines) == 0: sys.stderr.write("Envi.execute: no arguments\n") return False cleanArg = list() envCmd = cmdLines[0] for i in opt: tempLine = envCmd.replace(opt[i][0], "") if tempLine != envCmd: opt[i] = [opt[i][0], not opt[i][1]] # toggle the opt envCmd = tempLine # return False if opt["Debug"][1] is True: self.set_debug(True) # self._printall = True else: self.set_debug(False) # self._printall = False if opt["Print"][1] is True: for x in os.environ: sys.stderr.write(x + ":\n") for y in os.environ[x].split(os.pathsep): sys.stderr.write("\t" + y + "\n") # sys.stdout.write("") return True if fromPython is False: if opt["Clean"][1] is True or opt["ExistOnly"][1] is True: self.main_cleanup(clean_double=opt["Clean"][1], exist_only=opt["ExistOnly"][1]) return True if opt["Store"][1] is True: # build a pack file to store initial state self.store() return True if opt["Info"][1] is True: import dskenv c = BaseEnv.base_config() p = BaseEnv.base_pack() sys.stderr.write("config in: {}\npacks in: {}\n".format(c, p)) if 'dev' in dskenv.__file__: sys.stderr.write("envi: dev dskenv\n") else: sys.stderr.write("envi: released code\n") sys.stderr.write("envi: released code\n") helplist = self.get_help() sys.stderr.write("\n".join(helplist)) return True app = "" logfile = "" writefile = "" # search if app and logfile envArgs = envCmd.split(",") # split per config paternapp = re.compile(r'-a\s*[\w\d\.\%s-]*' % os.sep) paternlog = re.compile(r'-l\s*[\w\d\.\%s-]*' % os.sep) paterncache = re.compile(r'-w\s*[\w\d\.\%s-]*' % os.sep) for envarg in envArgs: # app m = paternapp.search(envarg) if m: stringfound = m.group() envarg = envarg.replace(stringfound, "") app = stringfound.replace("-a", "") app = app.strip() # log aclean = envarg.strip() m = paternlog.search(aclean) if m: stringfound = m.group() envarg = envarg.replace(stringfound, "") logfile = stringfound.replace("-l", "") logfile = logfile.strip() # write aclean = envarg.strip() m = paterncache.search(aclean) if m: stringfound = m.group() envarg = envarg.replace(stringfound, "") writefile = stringfound.replace("-w", "") writefile = writefile.strip() aclean = envarg.strip() if aclean != "": cleanArg.append(aclean) if opt["List"][1] is True: import dskenv import getpass # if self.info_from_environment(): # for obj in self.get_commands(): if writefile != "": is_d = False for x in cleanArg: # sys.stderr.write("---> %r\n" % x) if '-d' in x: # sys.stderr.write("---> hellp\n") is_d = True break try: f = open(writefile, "w") except: traceback.print_exc() return False # for obj in BaseEnv.pack_history( # os.environ.get('DSKENVPATH')): for obj in BaseEnv.command_history(): if is_d is False: # sys.stderr.write("---> %s\n" % obj) """FOR LATER IF NEEDED""" # paternd = re.compile("-D\s*[\w\d\.\-]*") # m = paternd.search(obj) # sys.stderr.write("-- %s" % m) # if m: # obj = obj.replace(m.group(),"") # obj = obj.strip() # sys.stderr.write("envi "+ obj + ";\n") f.write("envi " + obj + ";\n") else: # sys.stderr.write("--------> %s\n" % obj) f.write("envi " + obj + " -D %s;\n" % (getpass.getuser())) else: for obj in BaseEnv.command_history(): sys.stderr.write("envi " + obj + ";\n") c = BaseEnv.base_config() p = BaseEnv.base_pack() sys.stderr.write("#config in {}\n#packs in {}\n".format(c, p)) if 'dev' in dskenv.__file__: sys.stderr.write("#envi code dev\n") else: sys.stderr.write("#envi code released\n") return True if writefile != "" and len(cleanArg) == 0 and app == "": res = self.dump_os_as_shell(writefile) if res is True: sys.stderr.write("DONE\n") else: sys.stderr.write("ERROR: couldn't create %s\n" % writefile) return True if logfile != "" and os.path.exists(os.path.dirname(logfile)): self.startlog(logfile) self.setPath("ENVI_LOG", logfile) else: self.unsetPath("ENVI_LOG") # take a snapshot SAVE_OS = dict() SAVE_OS.update(os.environ) self.init_with_cmd(cleanArg) self.do_eval_pack() if opt["Reset"][1] is True: # self.unsetPath(BaseEnv.get_key_pack_info()) # self.unsetPath(BaseEnv.get_key_config_info()) self.unsetPath(BaseEnv.get_command_info()) else: if app != "": self.add_command("-a %s" % app) self.build_command_history() if app == "": if writefile == "": if fromPython is True: if opt['DictOnly'][1] is True: self.reset_cache() self.endlog() return True os.environ.update(self.get_environ(withRemoveCmd=False)) self.expand_vars(os.environ) newpath = list() for p in sys.path: if p.startswith(sys.prefix): newpath.append(p) if 'PYTHONPATH' in os.environ: newpath.extend(os.environ['PYTHONPATH'].split( os.pathsep)) sys.path = newpath # reset the sys.path self.reset_cache() self.endlog() return True else: self.echo_environ_diff_only(SAVE_OS) self.endlog() return True else: sys.stderr.write("write file %s\n" % writefile) self.write_environ(SAVE_OS, writefile) self.endlog() return True if fromPython is False: self.write_bash_history() # we still need to update the calling # shell with the command history cmd = [app] if len(cmdLines) == 2: apparg = cmdLines[1] cmd.extend(apparg.split()) # self.logfile("2") os.environ.update(self.get_environ(withRemoveCmd=False)) self.expand_vars(os.environ) self.reset_cache() # self.logfile("3") self.logfile("execute: %s" % " ".join(cmd)) thelog = self.getlog() p = None if thelog and opt["Deamon"][1] is True: sys.stderr.write("IN SUBProcess start\n") self.endlog() thelog = open(logfile, "a+") x = LaunchApp(cmd, thelog) x.start() else: if thelog: sys.stderr.write("IN SUBProcess start2\n") p = subprocess.Popen(" ".join(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True) if p.wait() != 0: self.logfile("ERROR: %s" % " ".join(cmd)) result = p.stdout.readlines() p.stdout.close() thelog.write("\n".join(result)) else: sys.stderr.write("IN SUBProcess start3\n") # sys.stderr.write("%s\n" % sys.stdout) # sys.stderr.write("err %s\n" % sys.stderr) p = subprocess.Popen(cmd, stdout=None, stderr=None, shell=True, close_fds=True) # import time # time.sleep(30) if p: self.logfile("Launched %r with processid %d" % (app, p.pid)) self.endlog()
def get_history_from_key(): return os.environ.get(BaseEnv.get_command_info(), "")