繁体   English   中英

在python中导入相同文件和函数名称的文件

[英]Importing file of same file and function name in python

src
 |
  -- Country
     |
      -- test_file.py -> test_file(function)
  -- State
     |
      -- test_file.py -> i want to run this file

我必须在State(当前工作目录)中运行test_file。 我必须从国家的test_file导入功能test_file。

使用路径

import sys
sys.path.append('../Country')
from test_file import *

print test_file()

当我运行文件时。 它说找不到role_name函数。 无法找到该功能。 但是,如果我将Country中的文件名从test_file更改为其他名称,它的工作正常。 我认为这个问题与某种模棱两可有关。

我需要为两个文件使用相同的名称。 还有其他解决此问题的方法吗?

sys.path.append('../Country') sys.path.insert(0, '../Country') sys.path.append('../Country')替换sys.path.append('../Country') sys.path.insert(0, '../Country')

由于您将Country模块附加在路径的末尾, test_file.py当前工作目录(州)中的test_file.py将具有优先权。 在路径的开头插入应该可以解决该问题。 也不要使用import *而是import role_path ,这样,如果找不到所需的对象,则import指令将失败,而不是默默地继续并让错误稍后触发。

但是,如果Country是一个合适的模块(是否带有__init__.py ,取决于Python版本),以这种方式导入函数会更干净:

from ..Country.test_file import role_path

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM