Python从命令行指定配置文件

时间:2014-08-25 17:33:25

标签: python command-line command config

我已经创建了一个python程序,我将编译成EXE但在此之前我想要一个命令行开关,让我指定我想要使用的配置文件。我的想法是有多个服务器用于不同目的的配置文件。我搜索过互联网,但对我看到的东西很困惑。关于如何做到这一点的任何建议将不胜感激......

1 个答案:

答案 0 :(得分:1)

您应该查看argparse模块,它可以为您处理命令行选项。

编辑:让我举个简单的例子。

import argparse

# create a new argument parser
parser = argparse.ArgumentParser(description="Simple argument parser")
# add a new command line option, call it '-c' and set its destination to 'config'
parser.add_argument("-c", action="store", dest="config_file")

# get the result
result = parser.parse_args()
# since we set 'config_file' as destination for the argument -c, 
# we can fetch its value like this (and print it, for example):
print(result.config_file)

然后,您可以继续使用result.config_file作为传递给脚本的配置文件的文件名。