【问题标题】:"from gtts import gTTS" works fine in python 2.7 but it does not work in python 3.5. Why?“从 gtts 导入 gTTS”在 python 2.7 中工作正常,但在 python 3.5 中不起作用。为什么?
【发布时间】:2019-05-18 19:08:15
【问题描述】:

我想执行这段代码:

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 仍然不存在... 有任何想法吗?谢谢

【问题讨论】:

    标签: python python-3.x python-2.7 import gtts


    【解决方案1】:

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

    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有点老了, 考虑使用更新的版本。

    【讨论】:

    • 非常感谢!!!确实,我尝试使用“$ python3 -m pip install gTTS”,然后确实可以进行导入!太棒了... !!!
    • 为什么会这样?我一生中第一次安装了 3.9 版的 Python 并且遇到了同样的问题。为什么它会默认使用一些过时的 pip 版本?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多