【问题标题】:Issue calling functions with argparse使用 argparse 发出调用函数
【发布时间】:2018-01-22 14:34:13
【问题描述】:

我在使用 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

无论传递什么参数。

【问题讨论】:

  • 您在命令行中使用什么命令来执行脚本?脚本中的哪个函数 exp()imp() 曾经被调用过(似乎它们只是被定义的)?
  • 你试过两个参数吗? python script.py arg1 arg2

标签: python function argparse


【解决方案1】:

这里有几个问题:

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

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

【讨论】:

    猜你喜欢
    • 2011-03-28
    • 2011-06-30
    • 2019-11-29
    • 1970-01-01
    • 2022-12-29
    • 2023-01-06
    • 2018-12-09
    • 2020-01-10
    相关资源
    最近更新 更多