Processing of paths when Python imports modules

Source: Internet
Author: User

The theoretical part when importing modules:

If you customize a module, the import is likely to be a problem, because the system automatically go back to the Sys.path output of these directories down to find, and the custom module is likely no longer these directories, it is necessary to add the human to use, so it leads to the following methods

The following is an example in Pycharm

The __file__ of the OS module can be used in pycharm to get the current directory
Import Osimport Sysproject_path = Os.path.dirname (Os.path.dirname (__file__)) Sys.path.append (Project_path) from core Import mainif __name__ = = ' __main__ ': main.home ()

  

Here are the usage scenarios in Linux

In Linux __file__ sometimes bad, through the Os.path.abspath (' start.py ') to the absolute path in the processing/usr/bin/env pythonimport osimport sysproject_path1 = Os.path.dirname (Os.path.abspath (' start.py '))  #在linux中使用__file__后面打印的时候竟然为空, so you can only write one more step, Get absolute path with Abspath in line processing project_path=os.path.dirname (project_path1) sys.path.append (project_path) print (Sys.path) Print (Project_path) from code import mainif __name__ = = ' __main__ ':    code.main.home ()

  

  

Processing of paths when Python imports modules

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.