无法处理"AttributeError:'module'对象没有属性'maketrans'"

use*_*712 0 python module

为了学习argparse模块,我从官方文档站点复制了一些代码.

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print (args.accumulate(args.integers))
Run Code Online (Sandbox Code Playgroud)

但是当我打字的时候

python argparseTesting.py
Run Code Online (Sandbox Code Playgroud)

在命令行中,出现以下错误:

test
case
with
strings
0
1
2
3
0
1
2
3
At Index 0 of our array, we have pens
At Index 1 of our array, we have staplers
At Index 2 of our array, we have flame-throwers
At Index 3 of our array, we have binders
Traceback (most recent call last):
  File "optparser_short.py", line 1, in <module>
    import argparse
  File "/usr/local/lib/python2.7/argparse.py", line 90, in <module>
    import textwrap as _textwrap
  File "/usr/local/lib/python2.7/textwrap.py", line 40, in <module>
    class TextWrapper:
  File "/usr/local/lib/python2.7/textwrap.py", line 82, in TextWrapper
    whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
AttributeError: 'module' object has no attribute 'maketrans'
Run Code Online (Sandbox Code Playgroud)

AttributeError中:'module'对象没有属性'maketrans',我读了几乎相同的问题.但那里的建议没有帮助.我有python版本2.7.11.

我希望有人能帮帮忙.

最好的祝福,

Mar*_*ers 5

几乎可以肯定string.py,在Python模块搜索路径中有一个本地Python文件.它掩盖了标准string库.

通过添加找到它:

import string; print(string.__file__)
Run Code Online (Sandbox Code Playgroud)

在您的argparseTesting.py脚本中运行它,就像之前运行它一样,然后重命名或删除string.py由该行所打印的任何文件文件/usr/local/lib/python2.7.不要忘记清理string.pyc它旁边的文件.您可能不得不多次执行此操作,具体取决于您sys.path拥有此类文件的位置数.不要这样做/usr/local/lib/python2.7/string.py,那就是库版本.

你的名字并不重要; 问题是,Python的应该不会发现它的名下string.它应该找到标准库模块.

确保在与argparseTesting.py脚本相同的上下文中运行它; Python查找额外模块的第一个位置是与脚本相同的目录,但是如果不运行脚本,则可以从不同的目录运行不同的代码,而不会看到正在导入的文件.

这里还有另外两种可能性,但只有在上面显示路径/usr/local/lib/python2.7/string.py或者路径时才适用/usr/local/lib/python2.7/string.pyc.在这种情况下,某些东西编辑了该文件(您需要将其恢复,2.7.11版本位于Python代码库中),或者其他一些代码已从string模块中删除该名称del string.maketrans.这样的代码必须通过siteuser配置挂钩运行.