解析配置模块中的选项

时间:2010-10-29 02:12:47

标签: python command-line python-3.x

我使用config模块将变量全局存储到所有模块。它是解析脚本参数的好地方吗? (注意:配置模块是我自己的模块,它只包含一堆全局变量。)

----- config.py -----
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-t", "--test", action = "store_true", dest = "test")
#add other options here
(options, args) = parser.parse_args()

------ file1.py ------
import config.py

if config.options.test:
   #do something

------ file2.py ------
import config.py

if config.options.test:
   #do something

我担心在“main”文件以外的文件中执行parse_args()函数(从命令行调用)。

1 个答案:

答案 0 :(得分:0)

你想做什么?有两种方法可以尝试 -

  1. 从命令行将参数值传递给您的程序(使用optparse)。
  2. 或写一个config.py将其导入您的程序&继续进行。
  3. 为什么要同时执行这两项操作(以及config文件中也是如此)?

    我发现您已将config模块写为.py(这很好)。但是这个文件应该包含最少的代码。只需配置设置。它可以帮助你保持代码和配置分开。

    我遵循的一般规则是,如果需要传递给我的程序的参数超过6-7,我使用配置文件。否则optparse就是。