• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python readline.set_history_length函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中readline.set_history_length函数的典型用法代码示例。如果您正苦于以下问题:Python set_history_length函数的具体用法?Python set_history_length怎么用?Python set_history_length使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了set_history_length函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: pythonrc_enable_history

def pythonrc_enable_history():
    import os
    import sys

    try:
        import readline
    except ImportError as e:
        sys.stderr.write(str(e) + " - Command-line history is disabled.\n")
    else:
        # The history file.
        PYHISTORY = os.path.expanduser('~/.pyhistory')

        # Restore command-line history.
        if os.path.isfile(PYHISTORY):
            readline.read_history_file(PYHISTORY)

        # Save command-line history when Python exits.
        try:
            import atexit
        except ImportError as e:
            sys.stderr.write(str(e) + " - Command-line history will not be saved when Python exits.\n")
        else:
            atexit.register(readline.write_history_file, PYHISTORY)

        # Set history size.
        readline.set_history_length(10000000)
开发者ID:woyizhidouzai,项目名称:dotfiles,代码行数:26,代码来源:pythonrc.py


示例2: __init__

    def __init__(self, options):
        """
        Constructor
        """
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        readline.set_completion_display_matches_hook(self.completer_print)
        try:
            readline.read_history_file(CLI_HISTORY)
        except IOError:
            pass
        readline.set_history_length(CLI_MAX_CMD_HISTORY)

        if not os.path.isdir(CLI_RESULT_HISTORY_FOLDER):
            os.system('rm -rf %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))
            os.system('mkdir -p %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))

        try:
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
        except:
            os.system('rm -rf %s' % CLI_RESULT_HISTORY_KEY)
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
            print "\nRead history file: %s error. Has recreate it.\n" % CLI_RESULT_HISTORY_KEY

        self.start_key = 'start_key'
        self.last_key = 'last_key'
        self.cli_cmd_func = {'help': self.show_help,
                             'history': self.show_help,
                             'more': self.show_more,
                             'quit': sys.exit,
                             'exit': sys.exit,
                             'save': self.save_json_to_file}
        self.cli_cmd = self.cli_cmd_func.keys()

        self.raw_words_db = self._parse_api_name(inventory.api_names)
        self.words_db = list(self.raw_words_db)
        self.words_db.extend(self.cli_cmd)
        self.words = list(self.words_db)
        self.is_cmd = False
        self.curr_pattern = None
        self.matching_words = None
        self.api_class_params = {}
        self.build_api_parameters()
        self.api = None
        self.account_name = None
        self.user_name = None
        self.session_uuid = None
        if os.path.exists(SESSION_FILE):
            try:
                with open(SESSION_FILE, 'r') as session_file_reader:
                    self.session_uuid = session_file_reader.readline().rstrip()
                    self.account_name = session_file_reader.readline().rstrip()
                    self.user_name = session_file_reader.readline().rstrip()
            except EOFError:
                pass

        self.hostname = options.host
        self.port = options.port
        self.no_secure = options.no_secure
        self.api = api.Api(host=self.hostname, port=self.port)
开发者ID:zstackorg,项目名称:zstack-utility,代码行数:60,代码来源:cli.py


示例3: init_history

 def init_history(self, histfile):
     if hasattr(readline, "read_history_file"):
         tryBackup = False
         try:
             tryBackup = not os.path.exists(histfile)
             if not tryBackup:
                 historyFileDesc = open(histfile)
                 historyFileDesc.seek(0, 2)
                 tryBackup = (historyFileDesc.tell() == 0)
                 historyFileDesc.close()
         except:
             tryBackup = False
         try:
             if tryBackup:
                 try:
                     if os.path.exists(histfile + '_backup'):
                         import shutil
                         shutil.copy(histfile + '_backup', histfile)
                 except:
                     pass
             readline.read_history_file(histfile)
         except IOError:
             pass
         readline.set_history_length(1000)
         atexit.register(self.save_history, histfile)
开发者ID:mohamed,项目名称:resp-sim,代码行数:25,代码来源:console.py


示例4: setup

def setup():
    # Create temporary directory for storing serialized objects.
    if not os.path.exists("_temp/"):
        os.mkdir("_temp/")

    # Configure log file for the application.
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s: %(message)s',
                        filename='cl_gui.log')
    logging.info("Starting application...")

    # Code snippet for recalling previous commands with the
    # 'up' and 'down' arrow keys.
    import rlcompleter
    import atexit
    import readline

    hist_file = os.path.join(os.environ['HOME'], '.pythonhistory')
    try:
        readline.read_history_file(hist_file)
    except IOError:
        pass

    # Set a limit on the number of commands to remember.
    # High values will hog system memory!
    readline.set_history_length(25)
    atexit.register(readline.write_history_file, hist_file)

    # Tab completion for GUI commands
    def completer(text, state):
        commands = Status.ALL_COMMANDS
        file_paths = []
        for dirname, dirnames, filenames in os.walk('.'):
            if '.git' in dirnames:
                # don't go into any .git directories.
                dirnames.remove('.git')
            # Add path to subdirectories
            file_paths.extend([os.path.join(dirname, sub_dir) for sub_dir in dirnames])
            # Add path to all filenames in subdirectories.
            file_paths.extend([os.path.join(dirname, filename) for filename in filenames])
            # Remove './' header in file strings.
            file_paths = [file.strip('./') for file in file_paths]

        options = [i for i in commands if i.startswith(text)]
        options.extend([f for f in file_paths if f.startswith(text)])

        try:
            return options[state]
        except IndexError:
            return None

    readline.set_completer(completer)

    # Bind tab completer to specific platforms
    if readline.__doc__ and 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind -e")
        readline.parse_and_bind("bind '\t' rl_complete")
    else:
        readline.parse_and_bind("tab: complete")
    del hist_file, readline, rlcompleter
开发者ID:LatencyTDH,项目名称:Pykit-Learn,代码行数:60,代码来源:cl_gui.py


示例5: save_history

 def save_history(self):
     if hasReadline and self._history_path:
         readline.set_history_length(1000)
         try:
             readline.write_history_file(self._history_path)
         except:
             pass
开发者ID:fedora-conary,项目名称:conary,代码行数:7,代码来源:shell.py


示例6: __init__

    def __init__(self, base, conf=None, path=None, task=None, wait=None):
        cmd.Cmd.__init__(self)

        self.base = urlparse.urlparse(base)
        self.user = getpass.getuser()
        self.hdfs = WebHDFSClient(self.base._replace(path='').geturl(), self.user, conf, wait)

        self.do_cd(path or self.base.path)

        if task:
            self.onecmd(' '.join(task))
            sys.exit(0)

        try:
            self.hist = os.path.join(os.path.expanduser('~'), os.environ.get('WEBHDFS_HISTFILE', '.webhdfs_history'))
            readline.read_history_file(self.hist)

        except IOError:
            pass

        try:
            readline.set_history_length(int(os.environ.get('WEBHDFS_HISTSIZE', 3)))
        except ValueError:
            readline.set_history_length(0)

        if os.access(self.hist, os.W_OK):
            atexit.register(readline.write_history_file, self.hist)
开发者ID:mk23,项目名称:webhdfs,代码行数:27,代码来源:prompt.py


示例7: save_history

def save_history(historyPath=historyPath):
    import readline
    try:
        readline.set_history_length(1000)
        readline.write_history_file(historyPath)
    except IOError:
        print 'skipping the history writing'
开发者ID:kalanand,项目名称:VPlusJets,代码行数:7,代码来源:pyroot_logon.py


示例8: __init__

    def __init__(self, *args, **kwargs):
        self.restshlib = restshlib.RestSHLib(global_data=self.global_data)
        self.prompt = self.cfg_prompt % {"login": self.login, "baseurl": self.baseurl}

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_file_max_lines)
        super(RestSH, self).__init__(*args, **kwargs)
开发者ID:jespino,项目名称:restsh,代码行数:7,代码来源:restcmd.py


示例9: history_init

 def history_init(self, filename, size):
     self.history_file = filename
     self.history_size = size
     if filename and os.path.exists(filename):
         readline.read_history_file(filename)
     readline.set_history_length(size)
     self.history_reset()
开发者ID:Gnucash,项目名称:gnucash,代码行数:7,代码来源:console.py


示例10: __init__

 def __init__(self):
     super().__init__()
     try:
         import readline
         readline.set_history_length(core.MAX_HISTORY_SIZE)
     except ImportError:
         pass
开发者ID:BwRy,项目名称:phpsploit,代码行数:7,代码来源:interface.py


示例11: setup

    def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            with open(self.history_file, 'a+') as history:
                if is_libedit():
                    history.write("_HiStOrY_V2_\n\n")

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        if is_libedit():
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")
开发者ID:zongdeiqianxing,项目名称:routersploit,代码行数:25,代码来源:interpreter.py


示例12: Interact

def Interact(session):
  import readline
  try:
    readline.read_history_file(session.config.history_file())
  except IOError:
    pass
  readline.set_history_length(100)

  try:
    while True:
      session.ui.block()
      opt = raw_input('mailpile> ').decode('utf-8').strip()
      session.ui.unblock()
      if opt:
        if ' ' in opt:
          opt, arg = opt.split(' ', 1)
        else:
          arg = ''
        try:
          Action(session, opt, arg)
        except UsageError, e:
          session.error(str(e))
  except EOFError:
    print

  readline.write_history_file(session.config.history_file())
开发者ID:gudbergur,项目名称:Mailpile,代码行数:26,代码来源:app.py


示例13: __init__

 def __init__( self ):
   cmd.Cmd.__init__( self )
   self.connected = False
   self.masterURL = "unset"
   self.writeEnabled = False
   self.modifiedData = False
   self.rpcClient = None
   self.do_connect()
   if self.connected:
     self.modificator = Modificator ( self.rpcClient )
   else:
     self.modificator = Modificator()
   self.identSpace = 20
   self.backupFilename = "dataChanges"
   self._initSignals()
   #User friendly hack
   self.do_exit = self.do_quit
   # store history
   histfilename = os.path.basename(sys.argv[0])
   historyFile = os.path.expanduser( "~/.dirac/%s.history" % histfilename[0:-3])
   if not os.path.exists( os.path.dirname(historyFile) ):
     os.makedirs( os.path.dirname(historyFile) )
   if os.path.isfile( historyFile ):
     readline.read_history_file( historyFile )
   readline.set_history_length(1000)
   atexit.register( readline.write_history_file, historyFile )
开发者ID:Kiyoshi-Hayasaka,项目名称:DIRAC,代码行数:26,代码来源:CSCLI.py


示例14: _init_history

 def _init_history(self):
     try:
         readline.set_history_length(100)
         readline.read_history_file(self._history_file)
     except IOError:
         pass
     atexit.register(self._save_history)
开发者ID:Ensembles,项目名称:ert,代码行数:7,代码来源:ertshell.py


示例15: Interact

def Interact(session):
    import readline
    try:
        readline.read_history_file(session.config.history_file())
    except IOError:
        pass

    # Negative history means no saving state to disk.
    history_length = session.config.sys.history_length
    if history_length >= 0:
        readline.set_history_length(history_length)
    else:
        readline.set_history_length(-history_length)

    try:
        prompt = session.ui.palette.color('mailpile> ',
                                          color=session.ui.palette.BLACK,
                                          weight=session.ui.palette.BOLD)
        while True:
            session.ui.block()
            opt = raw_input(prompt).decode('utf-8').strip()
            session.ui.unblock()
            if opt:
                if ' ' in opt:
                    opt, arg = opt.split(' ', 1)
                else:
                    arg = ''
                try:
                    session.ui.display_result(Action(session, opt, arg))
                except UsageError, e:
                    session.error(unicode(e))
                except UrlRedirectException, e:
                    session.error('Tried to redirect to: %s' % e.url)
开发者ID:Valodim,项目名称:Mailpile,代码行数:33,代码来源:app.py


示例16: _pythonrc_enable_history

def _pythonrc_enable_history():
    import atexit
    import os
    try:
        import readline
    except:
        return

    # "NOHIST= python" will disable history
    if 'NOHIST' not in os.environ:
        history_path = os.path.expanduser('~/.history/python')

        has_written = [False]

        def write_history():
            if not has_written[0]:
                readline.write_history_file(history_path)
                print('Written history to %s' % history_path)
                has_written[0] = True
        atexit.register(write_history)

        if os.path.isfile(history_path):
            try:
                readline.read_history_file(history_path)
            except IOError:
                pass
            
        readline.set_history_length(-1)
开发者ID:IndelibleStamp,项目名称:dotfiles,代码行数:28,代码来源:.pythonrc.py


示例17: __init__

 def __init__(self, config):
     self.config = config
     self._buffer = ''
     self.no_response = object()
     self.prompt = '>> '
     if HAS_READLINE and config['terms_history_file'] and int(config['terms_history_length']):
         readline.set_history_length(int(config['terms_history_length']))
         fn = os.path.expanduser(config['terms_history_file'])
         try:
             if not os.path.exists(fn):
                 with open(fn, 'w') as f:
                     f.write('# terms history\n')
             readline.read_history_file(fn)
         except Exception:
             pass
     address = '%s/%s' % (config['dbms'], config['dbname'])
     engine = create_engine(address)
     Session = sessionmaker(bind=engine)
     if config['dbname'] == ':memory:':
         from terms.core.terms import Base
         Base.metadata.create_all(engine)
         from terms.core.network import Network
         Network.initialize(Session())
     self.compiler = Compiler(Session(), config)
     register_exec_global(Runtime(self.compiler), name='runtime')
开发者ID:enriquepablo,项目名称:terms,代码行数:25,代码来源:repl.py


示例18: clear_history

 def clear_history(self):
     try:
         readline.clear_history()
     except AttributeError:
         len = self.get_max_length()
         readline.set_history_length(0)
         readline.set_history_length(len)
开发者ID:AppScale,项目名称:appscale,代码行数:7,代码来源:history.py


示例19: start

def start(**kwargs):
    shell = Civ4Shell(**kwargs)
    # completer = Completer(shell=shell)

    # Load history
    try:
        readline.read_history_file(PYCONSOLE_HIST_FILE)
    except IOError:
        shell.warn("Can't read history file")

    # Load help system in background thread
    # doc_thread = Thread(target=load_civ4_library)
    # doc_thread.start()

    # Start Input loop
    try:
        shell.cmdloop()
    except KeyboardInterrupt:
        shell.warn("Ctrl+C pressed. Quitting Civ4 shell.")
        shell.close()
    except TypeError:
        shell.warn("Type error. Quitting Civ4 shell.")
        shell.close()
    finally:
        shell.close()

    # Write history
    try:
        readline.set_history_length(100000)
        readline.write_history_file(".pyconsole.history")
    except IOError:
        shell.warn("Can't write history file")
开发者ID:YggdrasiI,项目名称:PBStats,代码行数:32,代码来源:Civ4Shell.py


示例20: __init__

 def __init__(self, env):
     self.__ps1 = "ZAS[%(cmdno)s/%(lineno)s]> "
     self.__ps2 = "ZAS[%(cmdno)s/%(lineno)s]: "
     self.__cmdno = 1
     self.__lineno = 1
     self.env = env
     readline.set_history_length(1000)
开发者ID:vulogov,项目名称:zas_proxy,代码行数:7,代码来源:clipsshell.py



注:本文中的readline.set_history_length函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python readline.set_pre_input_hook函数代码示例发布时间:2022-05-26
下一篇:
Python readline.set_completer_delims函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap