Reputation: 84
I have a main python3 file as follows:
import additionalfunctions
userIn = input("Select Function and command line arguments: ")
'additionalfunctions.py' is as follows:
def arbitraryfunction(arg):
print("you entered the value: " + str(arg))
The issue I am facing is that I need to select this function with with the 'input()' in the main python file, as well as pass the one argument to it. Does anyone know how to parse the variable 'userIn' in order to select and run a function, and pass arguments to it?
Any help you can give would be much appreciated!
Upvotes: 0
Views: 206
Reputation: 157
In addition to High-Octane answer, which is totally right, once you have the command line parameters, you can use exec()
to run the selected function and pass the arguments to it. Try this based on your own code:
def arbitraryfunction(arg):
print("you entered the value: " + str(arg))
allowed_functions = ['arbitraryfunction']
# write "arbitraryfunction 0" or similar when asked
userIn = input("Select Function and command line arguments: ")
args = userIn.split(" ")
if len(args) >= 2:
fun = args[0]
arg = args[1]
if fun in allowed_functions:
exec(fun + "(" + str(arg) + ")")
else:
print("Function not found. Please try again")
Then,you have to import additionalfunctions (I included it into the same script for simplicity) like this:
from additionalfunctions import *
Disclaimer: This should not be used in any production sensitive environment as it can execute malicious scripts.
Upvotes: -1
Reputation: 1112
You can use the default package argparse
And create a function like below.
Code:
import argparse
#>>>>>>>>>>>>>>>>>>>>>>> ARGUMENT PARSING <<<<<<<<<<<<<<<<<<<<<<<<<<<<
def args():
parser = argparse.ArgumentParser()
parser.add_argument('-A','--Arg1',type=int,help='I am Argument 1',required=False)
parser.add_argument('-B','--Arg2',type=str,help='I am Argument 2',required=True)
parser.add_argument('-C','--Arg3',type=str,help='I am Argument 3',required=True)
args = parser.parse_args()
print("PARSING ARGUMENTS COMPLETED")
argparse documentation : https://docs.python.org/3/library/argparse.html
Upvotes: 2