1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| ## my_module.py file print('Imported my_module...') test = 'Test String' def find_index(to_search, target): '''Find the index of a value in a sequence''' for i, value in enumerate(to_search): if value == target: return i return -1 ## test.py basic import my_module
courses = ['History', 'Math', 'Physics', 'CompSci'] index = my_module.find_index(courses, 'Math') print(index) # Imported my_module... # 1 ## test.py as import my_module as mm
courses = ['History', 'Math', 'Physics', 'CompSci'] index = mm.find_index(courses, 'Math') print(index) # Imported my_module... # 1 ## test.py from from my_module import find_index,test courses = ['History', 'Math', 'Physics', 'CompSci'] index = find_index(courses, 'Math') print(index) # Imported my_module... # 1 print(test) # Test String ## test.py from as from my_module import find_index as fi,test courses = ['History', 'Math', 'Physics', 'CompSci'] index = fi(courses, 'Math') print(index) # Imported my_module... # 1 print(test) # Test String ## sys.path: the path of modules to import from from my_module import find_index, test import sys courses = ['History', 'Math', 'Physics', 'CompSci'] index = find_index(courses, 'Math') # print(index) # print(test) print(sys.path) # ['C:\\Dev\\examples\\python\\python_examples',...] ## add path to sys.path or to PYTHONPATH # move my_module.py to new dir mymoduledir # rerun test.py, there is an error ModuleNotFoundError # solution 1: add mymoduledir to sys.path import sys sys.path.append('C:\Dev\examples\python\python_examples\mymoduledir') print(sys.path) # solution 2: set mymoduledir to PYTHONPATH set PYTHONPATH=C:\Dev\examples\python\python_examples\mymoduledir ## import existing libraries # random import random courses = ['History', 'Math', 'Physics', 'CompSci'] random_choice = random.choice(courses) print(random_choice) # math import math res = math.log2(2) print(res) # 1.0 # datetime import datetime today = datetime.date.today() print(today) # os import os # get current working directory print(os.getcwd())
|