這裏有一個2014的回答2011年的問題 -
的isort筆者,一個工具,清理進口,必須以滿足該核心庫進口前應責令PEP8要求搏鬥此相同的問題第三方進口。
我一直在使用這個工具,它似乎工作得很好。您可以將文件isort.py
中使用的方法place_module
,因爲它是開源的,我希望作者不會介意我在這裏再現邏輯:
def place_module(self, moduleName):
"""Tries to determine if a module is a python std import, third party import, or project code:
if it can't determine - it assumes it is project code
"""
if moduleName.startswith("."):
return SECTIONS.LOCALFOLDER
index = moduleName.find('.')
if index:
firstPart = moduleName[:index]
else:
firstPart = None
for forced_separate in self.config['forced_separate']:
if moduleName.startswith(forced_separate):
return forced_separate
if moduleName == "__future__" or (firstPart == "__future__"):
return SECTIONS.FUTURE
elif moduleName in self.config['known_standard_library'] or \
(firstPart in self.config['known_standard_library']):
return SECTIONS.STDLIB
elif moduleName in self.config['known_third_party'] or (firstPart in self.config['known_third_party']):
return SECTIONS.THIRDPARTY
elif moduleName in self.config['known_first_party'] or (firstPart in self.config['known_first_party']):
return SECTIONS.FIRSTPARTY
for prefix in PYTHONPATH:
module_path = "/".join((prefix, moduleName.replace(".", "/")))
package_path = "/".join((prefix, moduleName.split(".")[0]))
if (os.path.exists(module_path + ".py") or os.path.exists(module_path + ".so") or
(os.path.exists(package_path) and os.path.isdir(package_path))):
if "site-packages" in prefix or "dist-packages" in prefix:
return SECTIONS.THIRDPARTY
elif "python2" in prefix.lower() or "python3" in prefix.lower():
return SECTIONS.STDLIB
else:
return SECTIONS.FIRSTPARTY
return SECTION_NAMES.index(self.config['default_section'])
很明顯,你需要在類和的情況下使用這種方法設置文件。這基本上是一個已知核心庫導入的靜態列表的回退。
# Note that none of these lists must be complete as they are simply fallbacks for when included auto-detection fails.
default = {'force_to_top': [],
'skip': ['__init__.py', ],
'line_length': 80,
'known_standard_library': ["abc", "anydbm", "argparse", "array", "asynchat", "asyncore", "atexit", "base64",
"BaseHTTPServer", "bisect", "bz2", "calendar", "cgitb", "cmd", "codecs",
"collections", "commands", "compileall", "ConfigParser", "contextlib", "Cookie",
"copy", "cPickle", "cProfile", "cStringIO", "csv", "datetime", "dbhash", "dbm",
"decimal", "difflib", "dircache", "dis", "doctest", "dumbdbm", "EasyDialogs",
"errno", "exceptions", "filecmp", "fileinput", "fnmatch", "fractions",
"functools", "gc", "gdbm", "getopt", "getpass", "gettext", "glob", "grp", "gzip",
"hashlib", "heapq", "hmac", "imaplib", "imp", "inspect", "itertools", "json",
"linecache", "locale", "logging", "mailbox", "math", "mhlib", "mmap",
"multiprocessing", "operator", "optparse", "os", "pdb", "pickle", "pipes",
"pkgutil", "platform", "plistlib", "pprint", "profile", "pstats", "pwd", "pyclbr",
"pydoc", "Queue", "random", "re", "readline", "resource", "rlcompleter",
"robotparser", "sched", "select", "shelve", "shlex", "shutil", "signal",
"SimpleXMLRPCServer", "site", "sitecustomize", "smtpd", "smtplib", "socket",
"SocketServer", "sqlite3", "string", "StringIO", "struct", "subprocess", "sys",
"sysconfig", "tabnanny", "tarfile", "tempfile", "textwrap", "threading", "time",
"timeit", "trace", "traceback", "unittest", "urllib", "urllib2", "urlparse",
"usercustomize", "uuid", "warnings", "weakref", "webbrowser", "whichdb", "xml",
"xmlrpclib", "zipfile", "zipimport", "zlib", 'builtins', '__builtin__'],
'known_third_party': ['google.appengine.api'],
'known_first_party': [],
---剪斷---
我已經是一個小時到之前,我迷迷糊糊的isort模塊自己寫這個工具,所以我希望這也能幫助別人,以避免重新發明車輪!
這是http://stackoverflow.com/questions/5632980/list-of-all-imports-in-的一個粗略的副本python-3,不幸的是到目前爲止還沒有吸引任何特別有用的答案。 –