文章目錄
- 通用方法
- for example
- import the module
- import the module in a package:
- module's path
- pythonPath環境變量
- reference
- 建立包來引用module:
通用方法
- 通過import sys子產品,對sys.path寫入新的環境變量(即要用的那個子產品的所在目錄),可以調用sys.path.append(方法插入環境變量(臨時的))
for example
import the module
module_path_string="D:/OneDrive - pop.zjgsu.edu.cn/PythonPath/exp3/test_submodule_package"
sys.path.append(module_path_string)
# add 子產品是我自定義的一個子產品
import add
print(add.add_func(1,6))
"""inspect the sys.path:added just before: """
# for i in sys.path:
# for example:filter by environment variable contatins "exp"
# if "exp" in i:
# print(i)
import the module in a package:
""" 通過import sys子產品,對sys.path寫入新的環境變量(即要用的那個子產品的所在目錄),可以調用sys.path.append(方法插入環境變量(臨時的)) """
import sys
pack_path_string="d:/OneDrive - pop.zjgsu.edu.cn/pythonPath/exp3"
sys.path.append(pack_path_string)
# for i in sys.path:
# # for example:filter by environment variable contatins "exp"
# if "exp" in i:
# print(i)
""" 插入完畢,可以正常導入子產品(或其中的某個函數) """
from test_submodule_package.add import add_func
print(add_func(1,5))
module’s path
- 如果是包,就要在被作為包的目錄下存在(建立)一個
檔案作為該目錄是包的記号__init__.py
pythonPath環境變量
- 此系一個多值環境變量(可以取多個值,不同值間用
(windows)或;
(linux)隔開:
reference
- 指令行與環境 — Python
- 子產品 — Python
建立包來引用module:
- 這可能發生在需要引用子產品的源檔案和某個要被引用的子產品所在目錄是兄弟級别的目錄的時候
- 盡管可以建立包來引用,但還是要注意目前的工作目錄(以os.getcwd()所顯示的為準
- 如果不是,可以用os.chdir()來更改工作目錄
- 但如果這樣,還不如直接os.chdir()到指定目錄再導入module