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

Python readline.set_startup_hook函数代码示例

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

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



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

示例1: get

    def get(self, field, value=None):
        """Gets :field: value from stdin.

        :field: Field's name.
        :value: Default value for editing.
        :returns: Value got from stdin.

        """
        readline.set_startup_hook(lambda: readline.insert_text(
            value is not None and str(value) or ""
        ))
        try:
            value = input("{0}> ".format(field))
        except KeyboardInterrupt:
            print()
            exit(0)
        readline.set_startup_hook()
        if field == 'priority':
            try:
                value = int(value)
            except ValueError:
                if value == '':
                    return None
                print("Invalid priority value!")
                exit(0)
            else:
                if value not in [1, 2, 3, 4, 5]:
                    print("Invalid priority value!")
                    exit(0)
                return value
        return value
开发者ID:roryokane,项目名称:td,代码行数:31,代码来源:main.py


示例2: defaulter

 def defaulter():
     """define default behavior startup"""
     if _readline_available:
         readline.insert_text(default)
     readline.set_startup_hook(defaulter)
     readline.get_completer()
     readline.set_completer(completer)
开发者ID:gadeleon,项目名称:pwman3,代码行数:7,代码来源:tools.py


示例3: getinput

def getinput(question, default="", reader=raw_input,
             completer=None, width=_defaultwidth):  # pragma: no cover
    """
    http://stackoverflow.com/questions/2617057/\
            supply-inputs-to-python-unittests
    """
    if reader == raw_input:
        if not _readline_available:
            val = raw_input(question.ljust(width))
            if val:
                return val
            else:
                return default
        else:
            def defaulter():
                """define default behavior startup"""
                if _readline_available:
                    readline.insert_text(default)
                readline.set_startup_hook(defaulter)
                readline.get_completer()
                readline.set_completer(completer)

            x = raw_input(question.ljust(width))
            readline.set_completer(completer)
            readline.set_startup_hook()
            if not x:
                return default
            return x
    else:
        return reader()
开发者ID:gadeleon,项目名称:pwman3,代码行数:30,代码来源:tools.py


示例4: rlinput

def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        # This was raw_input, but that's deprecated in py3
        return input(prompt)
    finally:
        readline.set_startup_hook()
开发者ID:thompcinnamon,项目名称:QM-calc-scripts,代码行数:7,代码来源:interfaceToSumHills.py


示例5: get_user_input

def get_user_input(obj, attr, opts, no_prefill=False):
    if attr == 'collection' and not getattr(obj, attr) and obj.project:
        setattr(obj, attr, obj.project.collection)

    if opts:
        optlist = ', '.join(['%s=%s' % (k, v) for k, v in opts.items()])
        prompt = '%s [Options: %s]: ' % (attr, optlist)
    else:
        prompt = '%s: ' % attr
    if no_prefill or not getattr(obj, attr):
        prefill = ''
    else:
        if (hasattr(obj, 'relations') and attr in obj.relations) \
                or (getattr(obj, attr) and hasattr(getattr(obj, attr), 'id')):
            prefill = getattr(obj, attr).id
        else:
            prefill = getattr(obj, attr)
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    try:
        return raw_input(prompt)
    finally:
        readline.set_startup_hook()
开发者ID:frost-nzcr4,项目名称:clint,代码行数:25,代码来源:clint.py


示例6: do_history

 def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - long(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print "CloudMonkey history cleared"
         return
     elif len(historyArg) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(long(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in xrange(startIdx, endIdx):
         self.monkeyprint("%s %s" % (str(idx).rjust(numLen),
                                     readline.get_history_item(idx)))
开发者ID:waegemae,项目名称:cloudstack-cloudmonkey,代码行数:26,代码来源:cloudmonkey.py


示例7: getWithDefault

def getWithDefault(question, value):
    question += ": "
    readline.set_startup_hook(lambda: readline.insert_text(value))
    try:
        return ask(question)
    finally:
        readline.set_startup_hook()
开发者ID:mouillerart,项目名称:greyc-iota,代码行数:7,代码来源:utils.py


示例8: prompt

	def prompt(prompt, prefill=""):
		readline.set_startup_hook(lambda: readline.insert_text(prefill))
		try:
			data = raw_input(prompt)
			print
			return data
		finally: readline.set_startup_hook()
开发者ID:kaustubh-karkare,项目名称:todolist,代码行数:7,代码来源:todolist.py


示例9: rlinput

def rlinput(prompt, prefill=''):
    """kind of like ras_input but with readline support and pre-filled answer"""
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return raw_input(prompt)
    finally:
        readline.set_startup_hook()
开发者ID:Astroua,项目名称:CARTAvis,代码行数:7,代码来源:buildRelease.py


示例10: read_input

def read_input(prompt, prefill = ''):
    """
    Function to read input from stdin
    
    Args:
        prompt: Prompt for the input
        prefill: A default value for the input
    """
    
    try:
        if not prefill:
            raise Exception
            
        #if readline is present, use to prefill the input
        import readline as c_readline
        value, prefill = prefill, ''  #in this case we are resetting the prefill so as to not return the prefill
        c_readline.set_startup_hook(lambda: c_readline.insert_text(value))
    except ImportError:
        #otherwise modify the prompt to show the prefill
        c_readline = None
        prompt = '%s[%s] ' % (prompt, prefill)
    except:
        c_readline = None

    #Python 2.x vs 3.x
    try:
        c_input = raw_input
    except:
        c_input = input
    
    try:
        #read the input or return any prefill values
        return c_input(prompt) or prefill
    finally:
        c_readline and c_readline.set_startup_hook()  #unbind startup hook
开发者ID:webyog,项目名称:sealion-agent,代码行数:35,代码来源:constructs.py


示例11: export_gcal

def export_gcal(v, y, m, d, tid, sid):	
	cmd = []
	cmd.append("gcalcli")
	cmd.append("--calendar")
	readline.set_startup_hook(lambda: readline.insert_text(""))
	t = tabCompleter()
	t.createListCompleter(["calender", "NSC absences", "NSC shared calender"])
	readline.set_completer_delims('\t')
	readline.parse_and_bind("tab: complete")
	readline.set_completer(t.listCompleter)
	calender = raw_input("Name of calender: ").strip()
	cmd.append(calender)
	cmd.append("--title")
	v[y][m][d][tid][sid]["subtask title"]
	cmd.append(v[y][m][d][tid][sid]["subtask title"])
	cmd.append("--where")
	cmd.append("''")
	cmd.append("--when")
	dt = str(m)+ "/" + str(d) + "/" + str(y) + " " + v[y][m][d][tid][sid]["start"]
	cmd.append(dt)
	cmd.append("--duration")
	(h1, m1) = tuple(v[y][m][d][tid][sid]["start"].split(':'))
	(h2, m2) = tuple(v[y][m][d][tid][sid]["end"].split(':'))
	dur = str((int(h2) - int(h1)) * 60 + (int(m2) -int(m1)))
	cmd.append(dur)
	cmd.append("--description")
	cmd.append("''")
	cmd.append("--reminder")
	cmd.append("0")
	cmd.append("add")
	job = subprocess.Popen(cmd)
	job.wait()
	raw_input("Press enter to continue")
开发者ID:cbasu,项目名称:tasks,代码行数:33,代码来源:support.py


示例12: rlinput

def rlinput(prompt, prefill='', oneline=False, ctxkey=''):
    """
    Get user input with readline editing support.
    """

    sentinel = ''
    if prefill is None:
        prefill = ''
    
    def only_once(text):
        """ generator for startup hook """
        readline.insert_text(text)
        yield
        while True:
            yield

    savedhist = NamedTemporaryFile()
    readline.write_history_file(savedhist.name)
    ctxhistname = ".tl" + ctxkey + "history"
    ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname)
    try:
        readline.clear_history()
    except AttributeError:
        print "This readline doesn't support clear_history()"
        raise
    
    savedcompleter = readline.get_completer()
    try:
        ulines = uniqify(ctxhistfile)
        readline.read_history_file(ctxhistfile)
        readline.set_completer(HistoryCompleter(ulines).complete)
    except IOError:
        pass

    readline.parse_and_bind('tab: complete')
    saveddelims = readline.get_completer_delims()
    readline.set_completer_delims('') ## No delims. Complete entire lines.
    readline.set_completion_display_matches_hook(match_display_hook)
    gen = only_once(prefill)
    readline.set_startup_hook(gen.next)
    try:
        if oneline:
            edited = raw_input(prompt)
        else:
            print prompt
            edited = "\n".join(iter(raw_input, sentinel))

        if edited.endswith(r'%%'):
            ## Invoke external editor
            edited = external_edit(edited[0:-2])
        return edited
    finally:
        ## Restore readline state 
        readline.write_history_file(ctxhistfile)
        readline.clear_history()
        readline.read_history_file(savedhist.name)
        savedhist.close()
        readline.set_completer(savedcompleter)
        readline.set_completer_delims(saveddelims)
        readline.set_startup_hook()    
开发者ID:Michael-F-Ellis,项目名称:TransLily,代码行数:60,代码来源:rl_interface.py


示例13: main

def main():
    env = pickle.load(open(path.ENV, "r"))
    user = imp.load_source("settings", path.SETTINGS)

    readline.read_history_file(path.HISTORY)
    
    for component in user.CLIENT_COMPONENTS:
        component.initialize(env, user)
    
    for line in open(path.RC, "r"):
        execute(env, user, line.strip())
            
    while True:
        try:
            line = raw_input(user.PROMPT_FORMAT % env)
            readline.set_startup_hook(None)
            if not line:
                continue

        except EOFError:
            print
            readline.write_history_file(path.HISTORY)
            break
    
        execute(env, user, line)

    for component in user.CLIENT_COMPONENTS:
        component.terminate(env, user)
    
    pickle.dump(env, open(path.ENV, "w"))
开发者ID:fumieval,项目名称:Curtana,代码行数:30,代码来源:cui.py


示例14: silent_invariant_raw_input

def silent_invariant_raw_input(prompt,comp=None,wipe=False, echo = True,color = Colors.NONE,completion=None):
    prompt = color+prompt+Colors.ENDC
    if not Control.silent:
        readline.set_startup_hook(lambda: readline.insert_text(comp))
    if completion=="Files":
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(fileCompleter)
    elif not completion is None:
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(lambda a,b:listCompleter(a,b,completion))
    try:
        if Control.silent:
            prompt = ""
        if echo:
            ret = raw_input(prompt)
        else:
            ret = getpass.getpass(prompt)
            wipe = False
        if wipe:
            l = readline.get_current_history_length()
            if l > 0:
                readline.remove_history_item(l-1)
        return ret
    finally:
        if not Control.silent:
            readline.set_startup_hook()
        if not completion is None:
            readline.parse_and_bind("set disable-completion On")
            readline.set_completer(None)
            #readline.parse_and_bind("tab: \t")
            readline.set_completer_delims("")
开发者ID:bentheiii,项目名称:SecretService,代码行数:33,代码来源:ControlService.py


示例15: _rlinput

 def _rlinput(self, prompt, prefill):
     readline.set_startup_hook(lambda: readline.insert_text(prefill))
     try:
         return raw_input(prompt)
     finally:
         readline.set_startup_hook()
     return prefill
开发者ID:rgs1,项目名称:notes,代码行数:7,代码来源:notes_manager.py


示例16: getUserInWithDef

def getUserInWithDef(msg, default):
    readline.set_startup_hook(lambda: readline.insert_text(default))
    var = raw_input(colors.BOLDON + "%s: " % (msg) + colors.BOLDOFF)
    readline.set_startup_hook(lambda: readline.insert_text(''))
    if var == "":
        print("No input given, try again.")
        return getUserIn(msg)
    return var
开发者ID:chriswhitehat,项目名称:cirta,代码行数:8,代码来源:util.py


示例17: input_default

def input_default(prompt, default):
    def startup_hook():
        readline.insert_text(default)
    readline.set_startup_hook(startup_hook)
    try:
        return raw_input(prompt)
    finally:
        readline.set_startup_hook(None)
开发者ID:wadoon,项目名称:pyKWallet,代码行数:8,代码来源:kwallet_shell.py


示例18: raw_input_default

 def raw_input_default(prompt, value = None):
     if value:
         readline.set_startup_hook(lambda: readline.insert_text(value))
     try:
         return raw_input(prompt)
     finally:
         if value:
             readline.set_startup_hook(None)
开发者ID:connectical,项目名称:roar,代码行数:8,代码来源:posts_ui.py


示例19: prefill_input

def prefill_input(prompt, prefill):
    """prompt for input with supplied prefill text"""
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        result = input(prompt)
    finally:
        readline.set_startup_hook()
    return result
开发者ID:ftzm,项目名称:TaskLand,代码行数:8,代码来源:actions.py


示例20: getinput

def getinput(question, default="", width=_defaultwidth):
    if (not _readline_available):
        return raw_input(question.ljust(width))
    else:
        def defaulter(): readline.insert_text(default)
        readline.set_startup_hook(defaulter)
        x = raw_input(question.ljust(width))
        readline.set_startup_hook()
        return x
开发者ID:BackupTheBerlios,项目名称:pwman2-svn,代码行数:9,代码来源:cli.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python readline.write_history_file函数代码示例发布时间:2022-05-26
下一篇:
Python readline.set_pre_input_hook函数代码示例发布时间: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