代码之家  ›  专栏  ›  技术社区  ›  daniels

python将文件命名为与库相同的名称

  •  2
  • daniels  · 技术社区  · 16 年前

    我有以下脚本

    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 回复  |  直到 16 年前
        1
  •  7
  •   Vinko Vrsalovic    16 年前

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

    也就是说,您可以触摸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
    
        2
  •  4
  •   gimel    16 年前

    应该避免使用标准库模块名称命名python文件。

        3
  •  0
  •   Fred Larson    16 年前

    Python并没有提供一种限定模块的方法。您可以通过从sys.path中删除“”项或将其移动到末尾来完成此操作。我不推荐。

        4
  •  0
  •   André    16 年前

        5
  •  -1
  •   axblount    16 年前
    import getopt as bettername