You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pylint报import-error无法导入machinetranslation.translator模块

Pylint导入同目录模块报错问题排查

问题场景

编写翻译功能单元测试时,需要导入同目录下machinetranslation包translator模块内的english_to_french、french_to_english两个函数,编写导入语句后Pylint持续抛出Unable to import 'machinetranslation.translator'pylint(import-error)错误,移除导入路径中的machinetranslation前缀直接导入translator,仍然触发相同报错。

相关代码

单元测试文件代码

import unittest

from machinetranslation.translator import english_to_french, french_to_english

class TestMyModule(unittest.TestCase):

    def test_english_to_french(self):

        self.assertNotEqual(english_to_french("None"), "")

        self.assertEqual(english_to_french('Hello'), 'Bonjour')

    def test_french_to_english(self):

        self.assertNotEqual(french_to_english("None"), "")

        self.assertEqual(french_to_english('Bonjour'), 'Hello')

if __name__ == '__main__':
    unittest.main()

translator.py模块代码

import os
import json
import six
from dotenv import load_dotenv
from google.cloud import translate


#Api key and url


apikey = os.environ['AIzaSyC8ZLEGytCqTMcqvFV0AVh0wCEgBkRlHr4']

url = os.environ['https://console.cloud.google.com/apis/credentials?project=ferrous-amphora-352613']

#Translates english to french
# Initialize Translation client
def english_to_french(english_text="Hello", project_id="ferrous-amphora-352613"):

    client = translate.TranslationServiceClient()

    location = "global"

    parent = f"projects/{'ferrous-amphora-352613'}/locations/{'My First Project'}"

    # Translate text from English to French
    response = client.translate_text(
        request={
            "location": location,
            "parent": parent,
            "contents": [english_text],
            "mime_type": "text/plain",
            "source_language_code": "en-US",
            "target_language_code": "fr",
        }
    )

    # Display the translation for each input text provided
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))



# Translates french to english
# Initialize Translation client
def french_to_english(french_text="Bonjour", project_id="ferrous-amphora-352613"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    location = "global"

    parent = f"projects/{'ferrous-amphora-352613'}/locations/{'MyFirstProject'}"

    # Translate text from English to French
    response = client.translate_text(
        request={
            "location": location,
            "parent": parent,
            "contents": [french_text],
            "mime_type": "text/plain",
            "source_language_code": "fr",
            "target_language_code": "en",
        }
    )

    # Display the translation for each input text provided
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))


if __name__ == "__main__":
    pass

问题原因与修复方案

该问题不是单一原因导致,既包含Pylint配置问题,也存在代码本身的写法错误,分别修复即可:

1. Pylint导入报错修复

Pylint默认不会自动将当前项目目录加入Python模块搜索路径,同时如果包目录缺少标识文件也会导致识别失败,按以下步骤排查:

  • 确认machinetranslation目录下存在名为__init__.py的空文件,该文件是Python识别目录为可导入包的必要标识,缺少该文件时无论怎么写导入语句都会失败。
  • 配置Pylint搜索路径:在项目根目录新建.pylintrc文件,写入以下配置,将当前工作目录加入模块搜索路径:
[MASTER]
init-hook='import sys; sys.path.append(".")'
  • 如果使用VS Code等IDE,也可以直接在编辑器的Pylint扩展设置中,给Pylint添加启动参数--init-hook="import sys; sys.path.append('.')",不需要单独写配置文件。

2. 代码运行时错误修复

就算解决Pylint报错,现有代码运行时也会直接抛出异常,需要同步修复以下问题:

  • 环境变量读取写法错误:os.environ['key']的作用是读取系统中已配置的、key为传入参数的环境变量,直接把API Key、URL作为key传入会直接触发KeyError。如果不需要读取系统环境变量,直接给变量赋值即可:
# 修正后
apikey = "AIzaSyC8ZLEGytCqTMcqvFV0AVh0wCEgBkRlHr4"
url = "https://console.cloud.google.com/apis/credentials?project=ferrous-amphora-352613"
  • 翻译函数无返回值:两个翻译函数目前仅打印翻译结果,没有return语句返回值,单元测试的断言逻辑拿到的永远是None,会直接断言失败。需要在打印逻辑后添加返回值:
# 以english_to_french为例,修改遍历结果部分
for translation in response.translations:
    translated_res = translation.translated_text
    print("Translated text: {}".format(translated_res))
    return translated_res

french_to_english函数按相同逻辑添加返回值即可。

  • Google Cloud接口parent参数格式错误:parent参数格式要求为projects/{项目ID}/locations/{服务区域},你已经将location设为global,parent里的locations值应该和location参数保持一致,不能写自定义的项目名称,修正后写法:
parent = f"projects/{project_id}/locations/global"

内容的提问来源于stack exchange,提问作者MashCode20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 17:45:40