[Python] How to make PyCharm recognize dynamic imports for local scripts?

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm facing a peculiar issue with PyCharm and Python imports. I have a well-organized directory with all my "stable" code, and a separate area for local scripts that are more experimental and specific. Despite this, I want these local scripts to use the standard, solid libraries I've developed. This is how my repository are organize

    └─▶ $ 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
    └── ...


    To achieve this, I added the following code at the beginning of my local scripts:

    # 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)


    This works perfectly when running the scripts, but unfortunately, PyCharm can't resolve these dynamic imports. I've already tried manually extending the PYTHONPATH as suggested in various threads (like here: PyCharm and PYTHONPATH), but it doesn't solve the problem.

    This is a limitation because the IDE can't provide suggestions for the functions in these libraries, which are quite extensive.

    Does anyone have any ideas on how to resolve this particular issue?

    Continue reading...

Compartilhe esta Página