【问题标题】:Python specify config file from command linePython从命令行指定配置文件
【发布时间】:2014-10-18 22:06:52
【问题描述】:

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

【问题讨论】:

  • 看看argparse
  • 为什么不对配置文件使用命令行参数?

标签: python command-line command config


【解决方案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 作为传递给脚本的配置文件的文件名。

【讨论】:

  • 谢谢,我正在看,但我是一个巨大的新手,我对我所看到的有点困惑......如果你能提供任何额外的见解,我将不胜感激。 ..我会继续努力弄清楚...
  • 所以如果我理解我所看到的,我可以导入 argparse parser = argparse.ArgumentParser parser.add_argument('-c', action="store", dest="config") config = ConfigParser。 ConfigParser() config.readfp(open(config))
  • user3739525:试试看。
猜你喜欢
  • 2014-10-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2020-12-10
  • 2016-07-18
  • 2015-07-22
  • 1970-01-01
  • 2012-05-19
相关资源
最近更新 更多