python命名一个与lib相同的文件

dan*_*els 2 python

我有以下脚本

import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
    print key, "=>", value
Run Code Online (Sandbox Code Playgroud)

如果我命名这个getopt.py并运行它不会工作,因为它试图导入自己

有没有办法解决这个问题,所以我可以保留这个文件名,但是在导入时指定我想要标准的python库而不是这个文件?

基于Vinko答案的解决方案:

import sys
sys.path.reverse()
from getopt import getopt

opts, args = getopt(sys.argv[1:], "h:s")

for key,value in opts:
    print key, "=>", value
Run Code Online (Sandbox Code Playgroud)

Vin*_*vic 7

您不应将脚本命名为现有模块.特别是如果标准.

也就是说,您可以触摸sys.path来修改库加载顺序

~# cat getopt.py
print "HI"
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import getopt
HI

~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.remove('')
>>> import getopt
>>> dir(getopt)
['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望避免完全导入并以不同方式执行,如下所示:

import sys
sys.path.remove('')
from getopt import getopt
sys.path.insert(0,'')
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
    print key, "=>", value
Run Code Online (Sandbox Code Playgroud)