首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何重建此缓存目录python3 /cmd cmd

如何重建此缓存目录python3 /cmd cmd
EN

Stack Overflow用户
提问于 2021-06-27 00:20:56
回答 1查看 39关注 0票数 1

我想知道如何在python3中做这个简短的测试,python3支持cmd,但dircache不支持...目前只能在python2上工作,但希望将其更改为在python3上工作,谢谢!

代码语言:javascript
复制
#!/usr/bin/env python

import cmd
import dircache

class MyCmd(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = '(MyCmd)'

    def do_test(self, line):
        print('cmd test ' + line)

    def complete_test(self, text, line, begidx, endidx):
        """ auto complete of file name.
        """
        line = line.split()
        if len(line) < 2:
            filename = ''
            path = './'
        else:
            path = line[1]
            if '/' in path:
                i = path.rfind('/')
                filename = path[i+1:]
                path = path[:i]
            else:
                filename = path
                path = './'

        ls = dircache.listdir(path)
        ls = ls[:] # for overwrite in annotate.
        dircache.annotate(path, ls)
        if filename == '':
            return ls
        else:
            return [f for f in ls if f.startswith(filename)]



if __name__ == '__main__':
    mycmd = MyCmd()
    mycmd.cmdloop()

我尝试过使用它而不是dircache,但是没有成功

代码语言:javascript
复制
@lru_cache(32)
def cached_listdir(d):
     return os.listdir(d)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-29 00:49:17

在这里您可以查看load函数

代码语言:javascript
复制
import os
import glob
import cmd

def _append_slash_if_dir(p):
    if p and os.path.isdir(p) and p[-1] != os.sep:
        return p + os.sep
    else:
        return p

class MyShell(cmd.Cmd):
    prompt = "> "

    def do_quit(self, line):
        return True

    def do_load(self, line):
        print("load " + line)

    def complete_load(self, text, line, begidx, endidx):
        before_arg = line.rfind(" ", 0, begidx)
        if before_arg == -1:
            return # arg not found

        fixed = line[before_arg+1:begidx]  # fixed portion of the arg
        arg = line[before_arg+1:endidx]
        pattern = arg + '*'

        completions = []
        for path in glob.glob(pattern):
            path = _append_slash_if_dir(path)
            completions.append(path.replace(fixed, "", 1))
        return completions

MyShell().cmdloop()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68144253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档