0

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.

the_word
  • 15
  • 1
  • 3
  • `getattr(object, name)` but you are calling it as getattr(name,object) and also note that you don't even have a variable called `main` defined in your code – e4c5 Dec 23 '16 at 05:22
  • 2
    what is `main`? I think you mean `'main'` instead of `main` – sid-m Dec 23 '16 at 05:24
  • There is a main function contained within each of the imported functions Contact_parser, Notes_parser, Records_parser – the_word Dec 23 '16 at 05:27
  • @sid-m is right, you need return a string on `main` function otherwise `getattr` do nothing for you ! – dsgdfg Dec 23 '16 at 08:30

2 Answers2

0

getattr() functions takes the first argument as valid python entity (object/module...etc) and second argument as string.

In your case replacing the

getattr("%s_parse" % (t),main)

with

getattr(Contact_parse, 'main')

should work.

But if you modules name is in string form as in your case, probably you can try,

getattr(sys.modules[t + "_parse"], 'main')
  • Joshi, `getattr(sys.modules[t + "_parse"], 'main')` works perfectly. Thanks to @sid-m as well for noting the need for main to be a string value. – the_word Dec 23 '16 at 13:34
0

this is how it works for me, however all my functions are class methods.

getattr(ClassName(), functionName)(fargs_in)
rafalf
  • 425
  • 7
  • 16