0

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.

o-90
  • 17,045
  • 10
  • 39
  • 63
Jarl2.0
  • 205
  • 1
  • 3
  • 8
  • 2
    What command are you using from the command line to execute the script? Where in the script are either of the functions `exp()` or `imp()` ever called (it appears they are only defined)? – o-90 Aug 14 '17 at 17:55
  • Have you tried with two arguments? `python script.py arg1 arg2` – c2huc2hu Aug 14 '17 at 17:57

1 Answers1

1

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 --.

amphibient
  • 29,770
  • 54
  • 146
  • 240