Pythonプログラミングの講義29日目です。
今日の講義は、モジュールについて。内職はPythonアプリのexe化。
【講義内容】
- モジュール
【ワンポイント】
モジュール
modules/hello1.py
print('Hello Module1.')
modules/hello2.py
def hello(): print('Hello Module2.') print(f'Hello2: {globals()}')
modules/hello3.py
def hello(): print('Hello Module3.') hello()
modules/hello4.py
def hello(): print('Hello Module4.') print(f'__name__: {__name__}') hello()
modules/hello5.py
def hello(): print('Hello Module5.') def test(): hello() if __name__=='__main__': test()
main.py
import sys, site print(f'SITE PACKAGES: {site.getsitepackages()}') print(f'USER SITE PACKAGES: {site.getusersitepackages()}') sys.path.append('./modules') print(sys.path) import hello1 import hello2 import hello4 import hello5 def lfunc(): import hello3 from hello3 import hello from modules import hello3 from modules.hello3 import hello print(f'LOCLAS: {locals()}') print('*'*100) print(type(hello3), type(hello)) print('*'*100) print(f'GLOBALS: {globals()}') from hello3 import hello from hello4 import hello as h4 print('*'*100) print('Conflict:') hello() h4() print('*'*100) import hello3.hello import hello4.hello print('*'*100) print('Conflict:') hello3.hello() hello4.hello() print('*'*100) if __name__=='__main__': lfunc()
main2.py
def lfunc(): from modules import hello3 from modules.hello3 import hello print(f'LOCLAS: {locals()}') print('*'*100) print(type(hello3), type(hello)) print('*'*100) print(f'GLOBALS: {globals()}') if __name__=='__main__': lfunc()
環境変数(PYTHONPATH)
import os, sys import site from pathlib import Path print(os.getenv('PYTHONPATH')) if os.getenv('PYTHONPATH') == None: p = Path().joinpath('modules') print(p.resolve('.')) os.environ['PYTHONPATH'] = str(p.resolve('.')) + ';' print(os.getenv('PYTHONPATH')) site.addsitedir(str(p.resolve('.'))) print(sys.path) import hello1
【今日の積み上げ】
- Pythonの基礎