module_rel_file_path = os.path.join(module_path, module_file) module_abs_file_path = os.path.abspath(module_rel_file_path) # read source code from file with open(module_abs_file_path, 'r') as code_file: source_code = code_file.read() # create a module object mod = types.ModuleType(module_name) mod.__file__ = module_abs_file_path # set a reference in sys.modules sys.modules[module_name] = mod # compile the source code code = compile(source_code, filename=module_abs_file_path, mode='exec') # execute compiled source code exec(code, mod.__dict__) # add objects from executing code to mod.__dict__ namespace # DONE! # running from mod namespace mod.hello() # running from sys modules cache import module1 module1.hello()
now = datetime.datetime.now() print(f'{now.year}:{now.month}:{now.day}'+f"L{now.hour}:{now.mintue}:{now.second}") timeit.time.sleep(1) def hello(): print("\t안녕하세요!") print("\t여기는 hello()함수 안입니다. 함수를 실행하고 있는 중입니다.") print(f"\t여기는 {__name__}프로그램의 시작 지점입니다.") print(f"\t모듈 이름(__name__) : {__name__}") print(f"\t여기는 {__name__} 프로그램의 종료 지점입니다.") import module1 as module print() print(f"여기는 {__name__} 프로그램입니다.") print("import한 module의 hello() 함수를 호출합니다.") print() module.hello() print() print("import한 module의 hello()함수 호출이 끝났습니다.") print(f"모듈 이름 (__name__) : {__name__}") print() def hello(): print("\t안녕하세요!!") print("\t여기는 hello()함수 안입니다. 함수를 실행하는 중입니다.") if __name__ == "__main__": print(f"\t여기는 {__name__}프로그램의 시작 지점입니다.") print(f"\t모듈이름 (__name__) : {__name__}") print(f"\t여기는 {__name__}프로그램의 종료 지점입니다.")
def hello(): print('module2 says Hello!\nand...') module1.hello()
def hello(): print('Module2 says hello!\n...') module1.hello()
import module1 as m print(m.A) m.hello()
def hello(): print('module2 says hello\nand...') print(module1.hello())
def hello(): print("module2 says hello!\nand...") module1.hello()
def hello(): print('Module2 says Hello!') module1.hello()
def hello(): print("{0} says hello".format(__name__)) module1.hello()