質問

I have a string coming from the database. This string is the name of a file .py that is within a module. The structure is this:

files
├── file1.py
├── file2.py
└── __init__.py

The file1.py contain:

def file1(imprime):
    print(imprime)

The file2.py contain:

def file2(imprime):
    print(imprime)

I need to convert the string to a function that can be callable.

In main.py file I try:

import files
string = "file1.py"
b = getattr(file1, string)

text = 'print this...'

b(text)

Can anyone help me?

役に立ちましたか?

解決

You can use the import function to import the module by name and stick that on the files module.

Edit: Changes to show how to call the function

import os
import files
wanted_file = "file1.py"
# name of module plus contained function
wanted_name = os.path.splitext(wanted_file)[0]
# if you do this many times, you can skip the import lookup after the first hit
if not hasattr(files, wanted_name):
    module = __import__('files.' + wanted_name)
    setattr(files, wanted_name, module)
else:
    module = getattr(files, wanted_name)
fctn = getattr(module, wanted_name)
text = 'print this...'
fctn(text)

他のヒント

There are a couple of problems. The string in this case shouldn't be ".py" file name but instead be a module or function name, so file1.

file1 isn't in scope though, because you've imported files, and file1 the function is inside files.file1 the module.

You could have files/init.py declare the following:

from file1 import *
from file2 import *

If you want the file1 function and the file2 function to exist on files. Then you would do b = getattr(files, string).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top