2008-10-14 39 views
2

我有以下腳本蟒蛇名字一樣一個lib文件

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 

回答

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 
-1
import getopt as bettername 

這應該允許您調用getopt的作爲bettername。

+0

它在開發我做的事情時仍然會自行導入(getopt.py)而不是庫 – daniels 2008-10-14 16:28:26

4

你應該避免用標準庫模塊名命名你的python文件。

+0

,但這只是一種好奇心。 有人在論壇上有這個問題,我很好奇,如果有解決方法 – daniels 2008-10-14 16:31:34

+0

@daniels:有 - 使用唯一的名稱。 – 2008-10-14 17:28:17

0

Python不給你一種方法來限定模塊。您可以通過從sys.path中刪除條目或將其移動到最後來完成此操作。我不會推薦它。

0

那麼,你可以(重新)從sys.path移動目前的diretory,其中包含庫的可修改的搜索路徑,使其工作,如果你真的需要的話。