Skip to main content
 首页 » 编程设计

python之Argparse 与函数的交互

2024年11月24日11davidwang456

因此,对于我的作业,我必须使用 argparse 来解析 .cvs 文件并对它们运行计算。我很难弄清楚如何做到这一点。

我已经制作了所需的三个函数,但我不知道如何将它们正确地合并到我们给出的框架代码中。

请看,当我的程序被测试时,运行配置。将使用适当的参数和指定的 .cvs 文件进行编辑。到目前为止,我所做的工作是手动测试 cvs 文件,而不是使用 argparse 适本地调用/使用它们。我所做的工作甚至没有使用 argparse。

我在代码中使用 argparse 的唯一原因是它几乎没有解释就抛给了我们,我们必须与之交互才能获得正确的结果。事实证明,这对我来说非常困难(而且压力很大),所以任何朝着正确方向的插入都是值得赞赏的 - 我真的很想理解这里的逻辑。

我们得到的框架代码包括除了我的 grand_total 函数之外的所有内容,我把它留作示例:

import argparse 
 
 
def Grand_total(filepath): 
  """ 
  Calculates the total amount of avocado sales given data from  a .csv file. 
  """ 
  avo_price = open(filepath,"r") 
  avo_price.readline() # to skip the header  
  lines_list=avo_price.readlines() 
  sum = 0.0 
  for line in lines_list: 
    columns = line.split(",") 
    prices= float(columns[2]) 
    volume = float(columns[3]) 
    total = (round((prices * volume),2)) 
    price_list = [] 
    price_list.append(total) 
    for num in price_list: 
      sum = sum + num 
  print ("Total Sales:",(sum)) 
 
 
 
def parse_args(): 
    """ 
    parse_args takes no input and returns an Namespace dictionary describing the arguments selected 
    by the user.  If invalid arguments are selected, the function will print an error message and quit. 
    :return: Namespace with arguments to use 
    """ 
 
    parser = argparse.ArgumentParser("Read CSV input about avocados and print total amount sold") 
    parser.add_argument('--input', '-i', dest='input', required=True, type=str, 
                       help='input CSV file') 
 
    parser.add_argument('--group_by_region', '-r', dest='group_by_region', action='store_true', default=False, 
                       help='Calculate results per region (default: calculate for all regions)') 
    parser.add_argument('--organic', '-o', dest='organic', action='store_true', default=False, 
                       help='Only calculate for organic avocados (default: calculate for conventional and organic)') 
 
    return parser.parse_args() 
 
 
def main(): 
    """ 
    The main body of the program.  It parses arguments, and performs calculations on a CSV 
    """ 
 
    # get arguments entered by users 
    args = parse_args() 
 
    # TODO remove these print statements 
    # This code is provided as an example for how to interpret the results of parse_args() 
    print("Input file:      {}".format(args.Grand_total)) 
    print("Group by region: {}".format(args.city_total)) 
    print("Only organic:    {}".format(args.organic_total)) 
 
 
if __name__ == "__main__": 
    main() 

如果我运行它(包括其他功能), 我得到:

AttributeError: 'Namespace' object has no attribute 'Grand_total' 

请您参考如下方法:

argparse 的作用之一是将命令行参数收集到您可以轻松访问的 Namespace 对象中。 如果一切顺利,args 将如下所示:

Namespace(input='my_csv.csv', group_by_region=False, organic=False) 

然后您可以使用 args.input 访问您的输入路径。

如何重构程序的示例:

def main(): 
    args = parse_args()  # Note: you don't actually need a separate function for this 
    path = args.input 
    if args.group_by_region: 
        region_output = #  calculate for each region here 
        # do something with region output 
 
    else: 
        Grand_total(path) 

昨天我实际上使用 argparse 做了一个快速项目;你可以看看here ;请注意,参数存储在 separate file 中.