我认为这是个愚蠢的问题,但我不明白为什么我会得到以下结果
AttributeError: 'module' object has no attribute 'test'
运行我的test3.py时。
这是我的项目树:
.
├── __init__.py
├── test3.py
└── testdir
├── __init__.py
└── test.py
我的test3.py:
#!/usr/bin/python
import testdir
if __name__ == "__main__":
print(testdir.test.VAR)
我的test.py:
#!/usr/bin/python
import os
VAR=os.path.abspath(__file__)
我也尝试通过这种方式导入我的VAR:
from testdir.test import VAR
编辑: 现在这个可以工作了 - 感谢 @user2357112 - 但我仍然想知道如何在没有
from ... import ...
的情况下导入整个 test.py 文件(如果可能的话)。 :)
我尝试使用
import ..testdir
进行相对导入,但得到了 SyntaxError
。
如果我尝试
import testdir.test
我会得到一个NameError: name'test' is not defined
。
如何导入该文件?我有点困惑。
编辑之二:
抱歉,当我尝试
import testdir.test
时,我也将print(testdir.test.VAR)
修改为print(test.VAR)
。
这就是问题所在,我的错。
与:
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
它工作得很好,我认为导入
testdir.test
使得 test
在范围内单独存在(而不是 testdir.test
)。
对于给您带来的不便,我们深表歉意。 :S
尝试将
from .test import VAR
添加到 testdir/init.py。那么 test3.py 中的 import testdir
print testdir.VAR
可能会起作用。我同意这更多的是一种解决方法而不是解决方案。
要添加整个文件而不使用 import 语句,您可以使用 execfile
我终于成功地以这种方式工作了:
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
当我尝试使用
print(testdir.test.VAR)
时,我错误地将 print(test.VAR)
修改为 import testdir.test
。所以我遇到了这个名称错误。
我的错。
我知道这个已经很旧了,但我也有与
argparse
相关的相同错误。我有一个实例,如果您想运行测试,您可以运行脚本并通过 test
(可能是一种奇怪的方法,但我对此很陌生!)。它也会将 test
传递到 unittest.main()
。我用这个修复了它:
unittest.main(argv=['_'])
以下是我工作时的情况:
from tests import *
parser = argparse.ArgumentParser()
subparser = parser.add_subparsers(dest='command', title='Commands')
subcommand_parser = subparser.add_parser('test')
args.parse_args()
if args.command == 'test':
unittest.main(argv=['_'])