Python 命令行脚本:根据用户输入自动完成文件/目录
我正在编写一个在 Bash 终端内运行的 Python 程序(并且它已经依赖于 Bash 作为其环境)。 我有一个小设置例程,它要求用户提供位于其文件系统上的目录。 这就是我读取输入的方式:
print "Input:",
input = sys.stdin.readline().strip()
现在我希望用户能够使用现有文件或目录的名称自动完成他的输入。最好的方法是什么?我是否需要自己查找目录/文件并使用包 cmd
(如 这个例子)?或者是否有更简单的“内置”方法来做到这一点?
如果我能够在 os.system 中使用 Bash 自动完成功能,那就没问题了。但到目前为止我尝试的一切都没有成功。这就是我尝试过的:
os.system("read -e -p \"Input:\" INPUT")
但很奇怪:Bash 抱怨 read: 1: Illegal option -e
,尽管该命令在简单的 Bash 脚本中工作。但我需要 -e 修饰符来完成。
对于如何在 Python 控制台程序中自动完成文件/目录名有什么建议吗?
I'm writing a Python program which is running inside a Bash Terminal (and it already depends on Bash as its environment).
There I have a little setup routine, which asks the user for a directory which is located on his filesystem.
This is how I read the input:
print "Input:",
input = sys.stdin.readline().strip()
Now I want the user to be able to autocomplete his input with the name of existing files or directories. What's the best way to do that? Do I need to lookup the directories/files myself and use the package cmd
(as in this example)? Or is there an easier, "built-in" way to do that?
It would also be ok if i was able to use the Bash autocompletion with os.system. But everything that i tried so far wasn't successful. This is what I tried:
os.system("read -e -p \"Input:\" INPUT")
But it's strange: Bash complains read: 1: Illegal option -e
, although the command works inside a simple Bash script. But I need the -e modifier for the completion.
Any suggestions how I can do file/dirname autocompletion in an Python Console Program?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要查看 readline 模块。我在这里回答了一个类似问题,它展示了如何做文件名/目录名自动完成路径。如果您需要更多详细信息,请告诉我。
You want to checkout the readline module. I answered a similar question here, which shows how to do filename/dirname auto-completion of paths. Let me know if you need more detail.