Pycharm imports from Git Submodule

北慕城南 提交于 2020-08-05 05:04:52

问题


I have a python project in Pycharm, wherein there is a nested Git submodule. Here is the folder structure:

my-git-repo
    git-submodule-repo
        package1
           foo.py
           bar.py
    package2
        baz.py
    .gitmodules

The imports in git-submodule-repo are structured as follows:

foo.py:
from package1.bar import some_func

However, Pycharm doesn't recognize this and wants me to instead have the following:

foo.py:
from git-submodule-repo.package1.bar import some_func

This is problematic because I don't want to have to change all the imports in git-submodule-repo (doesn't seem like good practice and isn't scaleable) and git-submodule-repo has dashes in it which isn't valid Python syntax for an import (I can't rename the repo).

I also need a way to import from git-submodule-repo in my code. Something like this:

baz.py:
from git-submodule-repo.package1.bar import some_func

But of course without the dashes making it invalid syntax. Here is the content of .gitmodules in case its useful:

[submodule "git-submodule-repo"]
    path = git-submodule-repo
    url = https://github.com/SomeAccount/git-submodule-repo.git

Any help would be appreciated!


回答1:


Soultion 1
Use native PyCharm support by marking you submodule folders as Sources in Preferences -> Project -> Project Structure.
The drawback of this approach is that it will not allow you to run your code without PyCharm (e.g. from terminal on a remote server) unless you use PyCharm remote interpreter option (works in PyCharm Professional only).

Solution 2
Check out the solution proposed by @Kevin about general import of python files from git submodule. You may create soft link to the lib on interest in the root of the project. In your case the command will be:
$ ln -s git-submodule-repo.package1 package1
Then you will be able to import it with from package1.bar import some_func from foo.py.
The drawback of this approach is that it is not cross-platform e.g. you will not be able to run it from windows in case you need it.



来源:https://stackoverflow.com/questions/62463328/pycharm-imports-from-git-submodule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!