The normal writing Python program will have an executable bin.py file, if the file needs to import My_module inside the module defined, how should be set Sys.path
The folder directory structure is as follows, because the bin is not in the My_module sibling directory, but in the bin directory, if directly using the From My_module Import main call module will be an error, you need to put the corresponding upper level directory day21_ Lesson Add to Sys.path
One, using an absolute path to add
Import sys,ossys.path.append (R ' d:/blzfmima/python3_s3/day21/day21_lesson/') from My_module import Mainmain.run () Print (__name__) if __name__ = = ' __main__ ': Pass
Using an absolute path to add the corresponding directory to the Sys.path is equivalent to writing the program dead, once the directory structure has changed or replicated to other hosts will not be able to run
Second, use relative paths to add
__file__ variable is the name of the file
Os.path.dirname is the OS built-in method to take the path of the file here using two successive methods to fetch the file bin.py path is D:/blzfmima/python3_s3/day21/day21_lesson/bin Then fetch the path again for this path to get the required path d:/blzfmima/python3_s3/day21/day21_lesson/
Import Sys,osbase_dir = Os.path.dirname (Os.path.dirname (__file__)) sys.path.append (Base_dir) #sys. Path.append (R ' d:/ blzfmima/python3_s3/day21/day21_lesson/') from My_module import Mainmain.run () print (__name__) if __name__ = = ' __main__ ': Pass
The above can be in the pycharm normal implementation of the call, but in the terminal execution or error, because Pycharm will take the liberty to add absolute path
Third, the ultimate method uses Os.path.abspath to fetch the file bin.py absolute path and then uses two times os.path.dirname to fetch the path to the upper two layer and the path of this column d:/blzfmima/python3_s3/day21/day21_ lesson/
Import Sys,osbase_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (Base_dir) # Sys.path.append (R ' d:/blzfmima/python3_s3/day21/day21_lesson/') from My_module import Mainmain.run () print (__name__) if __name__ = = ' __main__ ': Pass
Python full stack day21 (the correct way to call the module path Basedir)