简体   繁体   English

从批处理文件运行 python 脚本时出现 ModuleNotFoundError

[英]ModuleNotFoundError when running python script from a batch file

I have a simple python script called sc.py that translates a word.我有一个名为sc.py的简单 python 脚本,可以翻译一个单词。 This is my code:这是我的代码:

#! python3

from googletrans import Translator
import sys

translator = Translator()

dest = 'hr'

if len(sys.argv) > 1:
    try:
        dest = sys.argv[2]
    except:
        pass

    translated = translator.translate(sys.argv[1],  dest = dest)
    print(translated.text)

The script works as expected when I run it from command line, for example like this:当我从命令行运行脚本时,该脚本按预期工作,例如:

python sc.py something it

And I get the expected result:我得到了预期的结果:

qualcosa

Then I created a batch file so I can call this script from anywhere by just writing translate .然后我创建了一个批处理文件,这样我就可以通过编写translate从任何地方调用这个脚本。 This is my batch file called translate.bat :这是我的批处理文件translate.bat

@py.exe D:\path\to\the\script\sc.py %*

I've added the folder where the batch file to the path, but when I try to run it I get ModuleNotFoundError like this:我已将批处理文件所在的文件夹添加到路径中,但是当我尝试运行它时,我得到ModuleNotFoundError

Traceback (most recent call last):
  File "D:\path\to\the\script\sc.py", line 3, in <module>
    from googletrans import Translator
ModuleNotFoundError: No module named 'googletrans'

I have no idea why this is happening, has anyone encountered anything similar?我不知道为什么会发生这种情况,有没有人遇到过类似的事情?

That could be there is multiple version of python installed or install googletrans for all version of python.那可能是安装了多个版本的python,或者为所有版本的python安装了googletrans

Use

python D:\path\to\the\script\sc.py %*

instead of代替

@py.exe D:\path\to\the\script\sc.py %* 

For python 3.7, type following in CMD:对于 python 3.7,在 CMD 中键入以下内容:

CD C:\Users\[path]\Continuum\anaconda3\Lib\site-packages

then:然后:

pip3 install googletrans

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM