在python中将字符串转换为函数(Convert string to function in python)

编程入门 行业动态 更新时间:2024-10-21 14:19:52
在python中将字符串转换为函数(Convert string to function in python)

我有一个来自数据库的字符串。 此字符串是模块中文件.py的名称。 结构是这样的:

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

file1.py包含:

def file1(imprime): print(imprime)

file2.py包含:

def file2(imprime): print(imprime)

我需要将字符串转换为可以调用的函数。

在main.py文件中我尝试:

import files string = "file1.py" b = getattr(file1, string) text = 'print this...' b(text)

谁能帮我?

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?

最满意答案

您可以使用导入功能按名称导入模块并将其粘贴在文件模块上。

编辑:更改以显示如何调用该函数

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)

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)

更多推荐

本文发布于:2023-07-05 06:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034421.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   转换为   中将   函数   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!