Jarl2.0
Jarl2.0

Reputation: 295

Issue calling functions with argparse

I'm having issues calling functions from the command line with argparse. I just want it to execute one of the functions defined in the script.

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)

When I try to call it with an argument I get:

error the follow arguments are required: i

No matter what argument is passed.

Upvotes: 0

Views: 73

Answers (1)

amphibient
amphibient

Reputation: 31212

A couple of problems here:

  1. You can't use action to call a defined function directly. However, you can set it to a boolean variable value using action='store_true' and then define your logic what to do when that variable is true (or false)
  2. Your functions have to be defined before you call them in the script.

This is what ended up working for me:

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

Also, make sure to prefix the abbreviated argument name with - and the full name with --.

Upvotes: 1

Related Questions