导入Python模块我有以下目录结构无法从不同的目录
/opt/juno/
+/opt/juno/__init__.py
+/opt/juno/lib/__init__.py
+/opt/juno/lib/gen_cert_request.py-Class CertDB->def Generate_cert()
+/opt/juno/tests/acceptance/cli_tests/cert-cli/test1.py
test1.py是我pytest功能,在那里我需要调用Generate_cert功能,但我无法导入模块。
我在/ opt/juno,/ opt/juno/lib,/ opt/juno/tests /,/ opt/juno/tests/acceptance /,/ opt/juno/tests/acceptance中创建了__init__.py
,/ opt/juno/tests/acceptance/cli-tests /,/ opt/juno/tests/acceptance/cli-tests/cert-cli,目录。
有关如何在test1.py中调用generate_cert函数的帮助?
我试过下面
[[email protected] pki-cert-cli]# pwd
/opt/juno/tests/acceptance/cli-tests/pki-cert-cli
[[email protected] pki-cert-cli]# ls -l /opt/juno/lib/
total 48
-rw-r--r--. 1 root root 5355 Sep 10 13:13 gen_cert_request.py
-rw-r--r--. 1 root root 5772 Sep 10 13:14 gen_cert_request.pyc
-rw-r--r--. 1 root root 0 Sep 10 13:08 __init__.py
-rw-r--r--. 1 root root 102 Sep 10 13:14 __init__.pyc
-rw-r--r--. 1 root root 4507 Sep 10 03:41 pki-wrapping-data.py
-rw-r--r--. 1 root root 1750 Sep 10 07:28 profile-xml.py
-rw-r--r--. 1 root root 29 Sep 9 09:22 README.md
-rw-r--r--. 1 root root 677 Sep 10 07:57 run_pki_commands.py
-rw-r--r--. 1 root root 941 Sep 10 12:05 run_pki_commands.pyc
drwxr-xr-x. 2 root root 4096 Sep 10 12:40 tests
[[email protected] pki-cert-cli]# python
Python 2.7.5 (default, Jun 25 2014, 10:19:55)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import juno.lib.gen_cert_request
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named juno.lib.gen_cert_request
>>> import lib.gen_cert_request
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named lib.gen_cert_request
我假设'''__init__.py'''应该替换sys.path方法吗? – mrashok 2014-09-11 02:20:30
不,'__init __。py'只是告诉python把这个目录看作一个包。导入时会忽略没有这种文件的目录。如果你可以使用它而不是'PYTHONPATH' /'sys.path',python将不得不在整个文件系统中搜索包含'__init __。py'的目录。请参阅模块搜索路径的[documentation](https://docs.python.org/2/tutorial/modules.html#the-module-search-path)。 – 2014-09-11 08:04:19