gpt4 book ai didi

Python:导入模块麻烦,取决于运行模式

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:19 24 4
gpt4 key购买 nike

我正在 virtualenv 中设置一个项目:

py-procr/
procr/
bin/
lib/
include/
core/
pcp.py
__init__.py
tests/
__init__.py
runner.py

pcp.py:

#!/usr/bin/env python

def hello(msg = "Hello, World!"):
print(msg)

def zero_pad(i, n):
return "%0{n}d"

if __name__ == '__main__':
hello("Main!")

运行者.py:

import unittest
from procr.core.pcp import *

class TestHelpers(unittest.TestCase):

def setUp(self):
self.alfa = "alfa"

def test_zero_pad(self):
padded_i = zero_pad(3, 5)
self.assertEqual(padded_i, "%0{n}d")

if __name__ == '__main__':
unittest.main()

这是运行模式:

(procr)a@s ~/spaces/python/py-procr $ python procr/core/pcp.py 
Main!
(procr)a@s ~/spaces/python/py-procr $ python tests/runner.py
Traceback (most recent call last):
File "tests/runner.py", line 2, in <module>
from procr.core.pcp import *
ImportError: No module named 'procr' ;; also 'core' and 'pcp' if you cut the import statement
(procr)a@s ~/spaces/python/py-procr $ python
Python 3.4.2 (default, Oct 8 2014, 13:44:52)
[GCC 4.9.1 20140903 (prerelease)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import procr.core.pcp
>>> import tests.runner ;; runner.py: from procr.core.pcp import *
>>> import tests.runner ;; runner.py: from core.pcp import *
>>> import tests.runner ;; runner.py: from pcp import *
>>> import core.pcp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'core'

我的Python路径:

>>> sys.path
['', '/home/alexey/spaces/python/py-procr/procr/lib/python34.zip', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4/plat-linux', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4/lib-dynload', '/usr/lib64/python3.4', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-linux', '/home/alexey/spaces/python/py-procr/procr/lib/python3.4/site-packages']
>>>

所以 IDE/编译器 (Eric) 很高兴; python REPL 也很高兴,但我无法运行我的测试。

最佳答案

尝试使用 -m 选项运行代码:

python -m tests.runner

PEP 338 中解释了原因:

Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts.

这里还有一些答案:What is the -m switch for in Python?

关于Python:导入模块麻烦,取决于运行模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27341525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com