python - Issue calling functions with argparse -


i'm having issues calling functions command line argparse. want execute 1 of functions defined in 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):     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):     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 try call argument get:

error follow arguments required: i

no matter argument passed.

a couple of problems here:

  1. you can't use action call defined function directly. however, can set boolean variable value using action='store_true' , define logic when variable true (or false)
  2. your functions have defined before call them in script.

this ended working me:

def exp(arg):     #replace below logic     print("in exp %s" % arg)  def imp(arg):     #replace below logic     print("in imp %s" % arg)  user = getpass.getuser() copyfolders = ['favorites']  parser = argparse.argumentparser()  #make sure prefix abbreviated argument name - , full name -- 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 prefix abbreviated argument name - , full name --.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -