"from gtts import gTTS" 在 python 2.7 中工作正常,但在 python 3.5 中不起作用。为什么?

"from gtts import gTTS" works fine in python 2.7 but it does not work in python 3.5. Why?

我要执行这段代码:

from gtts import gTTS
tts = gTTS('hello', lang='en')
tts.save('hello.mp3')

在 python (python 2.7.13) 中工作正常但在 python3 (python 3.5.3) 中不工作。

它在旧 python 中一直有效。现在,在一台新 PC(树莓派)上,我想开始使用 python3 (3.5.3),所以我尝试了,但没有成功。

由于是全新安装,可能没有安装gtts,所以我安装了:

pi@raspberrypi:~ $ pip install gTTS

我有这个:

Collecting gTTS
Downloading
...
...
...
Successfully built gTTS bs4 gtts-token
Installing collected packages: backports.functools-lru-cache, soupsieve, beautifulsoup4, bs4, click, idna, chardet, certifi, urllib3, requests, gtts-token, six, gTTS
Successfully installed backports.functools-lru-cache-1.5 beautifulsoup4-4.7.1 bs4-0.0.1 certifi-2019.3.9 chardet-3.0.4 click-7.0 gTTS-2.0.3 gtts-token-1.1.3 idna-2.8 requests-2.22.0 six-1.12.0 soupsieve-1.9.1 urllib3-1.25.2
pi@raspberrypi:/home $ 

我又试了一次,还是不行。 我尝试使用旧的 2.7 版本,令我惊讶的是,它可以正常工作。

在python工作:

pi@raspberrypi:/ $ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from gtts import gTTS
>>> 

在 python3

中不工作
pi@raspberrypi:~ $ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gtts import gTTS
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'gtts'
>>> 

然后,我注意到有 pip3 ! 当我这样做时

pi@raspberrypi:~ $ sudo pip3 install gTTS

gTTS 不存在,所以我做了

pi@raspberrypi:~ $ sudo pip3 install gTTS

但在这样做之后我收到红色文本和错误消息

 File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 643, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 315, in increment
    total -= 1
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

当我再次检查 pip list 时,gTTS 仍然不存在... 有任何想法吗?谢谢

你在抱怨你 运行 某个解释器并看到:

from gtts import gTTS
...
ImportError: No module named 'gtts'

或更简洁:

import gtts
...
ImportError: No module named 'gtts'

困难在于您从未为该解释器安装 gtts。

是的,你 运行 pip(或等同于 pip2), 它为您的 python2.7 口译员提供了极好的服务。 不,你永远不会 运行 pip3, 这可能适用于您的 python3.5 解释器。

以这种方式调用它可能会更好:

$ python3 -m pip install gTTS

那么你很确定sys.path在安装过程中会是什么, 包裹会落在正确的地方 import 找到它。

作为一个单独的项目,3.5有点老了, 考虑使用较新的版本。