使用 argparse 发出调用函数

Issue calling functions with 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)

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

error the follow arguments are required: i

无论传递什么参数。

这里有几个问题:

  1. 您不能使用action直接调用已定义的函数。但是,您可以使用 action='store_true' 将其设置为布尔变量值,然后定义您的逻辑在该变量为真(或假)时要做什么
  2. 脚本中的函数 have to be defined before you call them

这就是最终对我有用的东西:

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")

此外,请确保在缩写参数名称前加上 - 前缀,在全名前加上 --