I am looping through a directory to send specific files of interest (contained in a list) to their corresponding functions, which are named similarly to the items in the list.
import os,sys,argparse
import Contact_parse
import Notes_parse
import Records_parse
...
def file_distro(dir):
'''
This function distributes the source files to their relevant parser scripts
'''
file_types = ["Contact","Notes","Records"]
for filename in os.listdir(dir):
for t in file_types:
if filename.startswith(t) and filename.endswith(".xml"):
print("%s: %s") % (t,filename) # Troubleshooting, works
try:
func = getattr("%s_parse" % (t),main)
# Returns TypeError: getattr(): attribute name must be string
#func = getattr(Contact_parse, main)
# Tried hardcoding to troubleshoot,
# also returns TypeError: getattr(): attribute name must be string
#print("%s_parse" % t) # Troubleshooting, works
except AttributeError:
print("function not found: %s_parse.main" % (t))
else:
func()
else:
continue
The error received is:
getattr(): attribute name must be string
The getattr language was attempted based on searches here, and there was significant discussion between using getattr, local/globals, or a dict. I even tried hardcoding a module name, also to no avail. Any help is greatly appreciated.
getattr()
functions takes the first argument as valid python entity (object/module...etc) and second argument as string.In your case replacing the
with
should work.
But if you modules name is in string form as in your case, probably you can try,