Python,将Python代码字符串作为模块导入 [英] Python, import string of Python code as module

查看:81
本文介绍了Python,将Python代码字符串作为模块导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,您可以执行类似的操作以使用字符串文件名导入模块,并在本地名称空间上为其变量分配一个变量.

In python you can do something like this to import a module using a string filename, and assign its namespace a variable on the local namespace.

x = __import__(str)

我想知道是否有一个相关函数将采用一串Python代码,而不是带有Python代码的文件路径,并将其命名空间作为变量返回.

I'm wondering if there is a related function that will take take a string of Python code, instead of a path to a file with Python code, and return its namespace as a variable.

例如,

str = "a = 5";
x = importstr(str)
print x.a
#output is 5

我意识到我可以将字符串写入文件,然后在其上使用__import__,但我想尽可能跳过中间文件.

I realize that I could write the string to a file, then use __import__ on it, but I'd like to skip the intermediate file if possible.

这样做的原因是我正在尝试使用python进行元编程,这似乎是我正在做的事情的一个很好的解决方案.

The reason for this is that I'm experimenting with metaprogramming in python, and it seems like a good solution to what I'm doing.

推荐答案

这是一个示例,它使用 imp模块动态创建模块对象

Here's an example of dynamically creating module objects using the imp module

这篇关于Python,将Python代码字符串作为模块导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆