Python 库中的简单终端文件选择器

Simple terminal file chooser in Python libraries

提问人:Marius 提问时间:11/13/2012 最后编辑:Marius 更新时间:11/13/2012 访问量:1801

问:

我编写了几个简单的命令行/终端 Python 程序来解析我们在心理学实验室中使用的实验运行软件中的数据文件。这些程序将由通常精通计算机的人使用,但不一定能跟上带有标志的成熟 unix 风格命令的速度,所以我通常只是让程序问一些问题,比如“你想处理哪个文件?”,并让用户从列表中选择,如下所示:

import textwrap
import os
import sys

def get_folder():
    """ Print a numbered
    list of the subfolders in the working directory
    (i.e. the directory the
    script is run from),
    and returns the directory
    the user chooses.
    """
    print(textwrap.dedent(
    """
    Which folder are your files located in?
    If you cannot see it in this list, you need
    to copy the folder containing them to the
    same folder as this script.
    """
    )
    )
    dirs = [d for d in os.listdir() if os.path.isdir(d)] + ['EXIT']
    dir_dict = {ind: value for ind, value in enumerate(dirs)}
    for key in dir_dict:
        print('(' + str(key) + ') ' + dir_dict[key])
    print()
    resp = int(input())
    if dir_dict[resp] == 'EXIT':
        sys.exit()
    else:
        return dir_dict[resp] 

Python 库中是否有这些类型的文件选择器的实现?我通常只是在需要的时候自己快速实现它们,但我最终不得不将代码从一个文件复制并粘贴到另一个文件,并针对我使用它们的特定情况进行修改。

python 终端

评论

2赞 David 11/13/2012
您可以打开一个文件对话框。这里有一些想法。
0赞 TJD 11/13/2012
如果您要将此类代码复制并粘贴到多个文件中,您可能会想到一种方法将其构建到您自己的可重用库中,您只需为每个特定用例导入该库即可。
0赞 Marius 11/13/2012
@David 谢谢,我担心在一些非常简单的代码中添加很多与 GUI 相关的繁琐,但看起来很简单。tkFileDialog

答: 暂无答案