对于这种问题,你有多种解决方案:
在每台机器上创建环境变量,并在脚本中执行以下操作:
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。