Python 将文件命名为与库相同

2 投票
5 回答
372 浏览
提问于 2025-04-11 09:34

我有一个这样的脚本

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

如果我把这个文件命名为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

5 个回答

0

好吧,如果你真的需要这样做,你可以把当前目录从 sys.path 中移除。sys.path 是一个可以修改的库搜索路径,里面包含了 Python 查找库的地方。

4

你应该避免把你的Python文件命名为标准库模块的名字。

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']

另外,你可能想避免使用完整的导入方式,可以尝试其他的方法,比如这样:

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

撰写回答