使用argparse发出调用函数

时间:2017-08-14 17:29:38

标签: python function argparse

我遇到了使用argparse从命令行调用函数的问题。我只是希望它执行脚本中定义的一个函数。

import os
import shutil
import getpass
import argparse


user = getpass.getuser()
copyfolders = ['Favorites']

parser = argparse.ArgumentParser()
parser.add_argument('e', action='store')
parser.add_argument('i', action='store')
args = parser.parse_args()


def exp(args):
    for folder in copyfolders:
        c_path = os.path.join("C:", "/", "Users", user, folder)
        l_path = os.path.join("L:", "/", "backup", folder)
        shutil.copytree(c_path, l_path)

def imp(args):
    for folder in copyfolders:
        l_path = os.path.join("L:", "/", "backup", folder)
        c_path = os.path.join("C:", "/", "Users", user, folder)
        shutil.copytree(l_path, c_path)

当我尝试用参数调用它时,我得到:

  

错误需要以下参数:i

无论传递什么参数。

1 个答案:

答案 0 :(得分:1)

这里有几个问题:

  1. 您无法使用action直接调用已定义的函数。但是,您可以使用action='store_true'将其设置为布尔变量值,然后定义逻辑在该变量为true(或为false)时要执行的操作
  2. 您在脚本中的功能have to be defined before you call them
  3. 最终为我工作的是:

    def exp(arg):
        #replace below with your logic
        print("in exp for %s" % arg)
    
    def imp(arg):
        #replace below with your logic
        print("in imp for %s" % arg)
    
    user = getpass.getuser()
    copyfolders = ['Favorites']
    
    parser = argparse.ArgumentParser()
    
    #make sure to prefix the abbreviated argument name with - and the full name with --
    parser.add_argument('-e', '--exp', action='store_true', required=False)
    parser.add_argument('-i', '--imp', action='store_true', required=False)
    args = parser.parse_args()
    
    isExp = args.exp
    isImp = args.imp
    
    if isExp:
        exp("foo")
    
    if isImp:
        imp("bar")
    

    另外,请确保将缩写参数名称加上-前缀,并使用--加上全名。

相关问题