【问题标题】:how to locate a same folder on different machines on different directory?如何在不同目录的不同机器上找到相同的文件夹?
【发布时间】:2019-11-20 02:13:08
【问题描述】:

我在目录/home/ubuntu/Desktop/Pythontraining 中有两个名为StudentFaculty 的文件夹。我需要在Student 文件夹中保存总共10 个文件,在Faculty 文件夹中保存3 个文件。我需要在另一个系统中执行相同操作,其中StudentFaculty 文件夹存在于不同的目录中(比如:@ 987654328@).如何在不硬编码路径的情况下将文件存储到两台不同机器上的各自文件夹中?

【问题讨论】:

    标签: python file directory hard-coding


    【解决方案1】:

    对于这种问题,你有多种解决方案:

    在每台机器上创建环境变量,并在脚本中执行以下操作:

    import os
    student_path = os.environ['STUDENT_PATH']
    faculty_path = os.environ['FACULTY_PATH']
    
    print(student_path, faculty_path)
    

    个人意见:我不喜欢使用环境变量来配置我的脚本,因为你选择的可能会被其他软件使用 + 调试总是很乱


    使用arguments

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--student")
    parser.add_argument("-f", "--faculty")
    
    args = parser.parse_args()
    student_path = args.student
    faculty_path = args.faculty
    
    print(student_path, faculty_path)
    

    然后像这样调用你的脚本并根据机器调整这一行

    python <yourscript> -s <student_path> -f <faculty_path>
    

    个人意见:当我想控制脚本上的少量参数以改变其行为(冗长,cpus 的 nb,...)时,我会使用参数。


    创建一个配置文件并使用configparser

    config.ini 文件

    [Paths]
    student_path=<path_on_machine>
    faculty_path=<path_on_machine>
    

    脚本用法:

    import configparser
    
    config = configparser.ConfigParser()
    config.read('config.ini')
    student_path = config.get('Paths', 'student_path')
    faculty_path = config.get('Paths', 'faculty_path')
    
    print(student_path, faculty_path)
    

    然后在每台机器上部署不同的config.ini 文件(ansible 之类的工具可以帮助您自动执行此操作)

    个人意见:我在新机器上部署时需要调整参数时使用配置文件。我不喜欢为此目的使用参数,因为我不想在每次使用脚本时都指定相同的值(通常这类参数没有好的默认值)。


    创建模块

    您也可以创建一个模块来存储这些参数,而不是一个配置文件。

    my_config.py

    student_path="<path_on_machine>"
    faculty_path="<path_on_machine>"
    

    然后导入

    脚本.py

    import my_config
    
    print(my_config.student_path, my_config.faculty_path)
    

    我对配置文件和配置模块没有任何个人意见。如果您想要一些比较元素,请阅读this

    【讨论】:

      【解决方案2】:

      您可以使用walk 库来查找目标文件夹路径。如果每个搜索名称只有一个文件夹,则效果最佳:

      import os
      
      start = "/home/"
      
      for dirpath, dirnames, filenames in os.walk(start):
          found = False
          for dirname in dirnames:
              if dirname == 'Student':
                  full_path = os.path.join(dirpath, dirname)
                  found = True
                  break
          if found:
              break
      

      输出:

      /home/.../学生

      【讨论】:

      • 如果文件夹'Student'出现在多个目录中怎么办?
      • 我会说使用 walk 而不是配置文件很危险。您无法确定脚本的行为(尤其是如果您有多个学生目录),并且您可能会覆盖重要文件。小心点。
      猜你喜欢
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      相关资源
      最近更新 更多