You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何让PyCharm识别本地脚本中的动态导入?

如何让PyCharm识别本地脚本中的动态导入?

我在使用PyCharm和Python导入时遇到了一个棘手的问题:我把稳定的核心代码和实验性的本地脚本分开存放,但希望本地脚本能调用核心库。

我的仓库目录结构是这样的:

└─▶ $ tree codeDir
codeDir
├── README.md
├── bambooLocalScript
│   ├── countProcessedClass.sh
│   ├── generate_ApexTestCatalog
│   │   ├── apex_src_test_heuristic_split.py
│   │   ├── apex_src_test_heuristic_split_progressive.py
│   │   ├── generate-apex-test-mapping.sh
│   │   └── process_catalog_trunk_sort.py
│   ├── list_large_files.py
│   └── prettierRunCountList.sh
└── script
    ├── enelPyLib
    │   ├── __init__.py
    │   ├── sfUtility.py
    │   └── ...
    ├── epm.py
    ├── fileGitExtract.py
    └── ...

为了让本地脚本能找到核心库,我在脚本开头加了这段动态添加路径的代码:

# apex_src_test_heuristic_split_progressive.py
import os
import sys

# Add the path of the script folder to PYTHONPATH
script_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'script'))
if script_path not in sys.path:
    sys.path.insert(0, script_path)

try:
    from myPyLib import sfUtility as sfUtil
except ModuleNotFoundError as e:
    print(f"Error: {e}. Make sure the path is correct and that the directory contains a __init__.py file.")
    sys.exit(1)

运行脚本时这段代码完全没问题,但PyCharm就是识别不了这种动态导入——我试过手动扩展PYTHONPATH,可还是没用。

这就很麻烦了,因为IDE没法给这些核心库的函数提供代码提示,而这些库的功能又挺多的。

有没有大佬知道怎么解决这个问题?

备注:内容来源于stack exchange,提问作者Emanuele Alfano

火山引擎 最新活动