Python从命令行指定配置文件

0 投票
1 回答
1641 浏览
提问于 2025-04-18 18:28

我写了一个Python程序,打算把它转换成EXE文件。不过在这之前,我想加一个命令行选项,这样我就可以指定想用的配置文件。我想准备多个配置文件,分别用于不同的目的。我在网上查了很多资料,但看到的内容让我有点困惑。如果有人能给我一些建议,我会非常感激……

1 个回答

3

你可以看看 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 来作为传给脚本的配置文件的文件名。

撰写回答