Skip to main content
 首页 » 编程设计

python之更好的命令行解析 python

2025年05月04日13xing901022

使用 argparse,我创建了一个小脚本,其中包含用于我的分析程序的命令行解析器,它是自制 python 包的一部分。它工作得很好,但我不太喜欢如何控制它。

这是代码在脚本中的样子

def myAnalysis(): 
 
    parser = argparse.ArgumentParser(description=''' 
        lala''') 
    parser.add_argument('-d', '--data',help='') 
    parser.add_argument('-e', '--option_1', help='', default=False, required=False) 
    parser.add_argument('-f', '--option_2', help='', default=False, required=False) 
 
 
    # combine parsed arguments 
    args = parser.parse_args()code here 

除此之外还有一些在分析包的设置文件中

entry_points={ 
          'console_scripts': [ 
              'py_analysis = edit.__main__:myAnalysis' 
          ] 

正如我所说,这没有任何问题。要分析我必须使用的一些数据

py_analysis --data path_to_data_file 

有时,我需要一些选项。为此,它可能看起来很普通

py_analysis --data path_to_data_file --option_1 True --option_2 True 

在我个人看来,这有点丑陋。我更喜欢类似的东西

py_analysis path_to_data_file --option_1 --option_2 

我很确定这是可能的。我只是不知道如何

请您参考如下方法:

使用store_true 操作

parser.add_argument('-e', '--option_1', help='', default=False, action ='store_true') 

然后只需添加到命令行 --option_1 即可将其值设置为 True。