我有两个 Python 文件。其中一个试图导入第二个。我的问题是第二个文件的名字是 math.py,我无法改变它。当我试图调用 math.py 中的函数时,因为全局 math 模块的存在,我无法实现。如何导入本地文件而不是全局文件?我正在使用 Python 2.7,并且这是(大致)我的导入语句:
cstr = "math"
command = __import__(cstr)
稍后我尝试:
command.in_math_py_not_global()
编辑:更完整的示例:
def parse(self,string):
clist = string.split(" ")
cstr= clist[0]
args = clist[1:len(clist)]
rvals = []
try:
command = __import__(cstr)
try:
rvals.extend(command.main(args))
except:
print sys.exc_info()
except ImportError:
print "Command not valid"
test.py
的文件,并在同一目录下创建了一个math.py
文件,使用import math
导入。一切都正常工作,我可以毫无问题地在自己的math.py
中调用math.foo()
。 - Greg Hewgill