简体   繁体   English

如何从不同的文件中动态导入 VSCode 的模块?

[英]How to import modules from different files ifor VSCode dynamically?

I am having an issue with VSCode.我在使用 VSCode 时遇到问题。 I tested the same directory and files in PyCharm and I don't need to write another code to recognize my modules.我在 PyCharm 中测试了相同的目录和文件,我不需要编写其他代码来识别我的模块。 The interpreter immediately runs the code.解释器立即运行代码。 I just need to use ie from folder_module import module as np .我只需要使用 ie from folder_module import module as np In VSCode this is very complex and after a lot of research in the internet I didn't find any helpful solution.在 VSCode 中,这非常复杂,在互联网上进行了大量研究后,我没有找到任何有用的解决方案。

I don't want to use sys.path.append('datapath_folder') (which works) or any similar solution because I will transfer the files into another computer.我不想使用sys.path.append('datapath_folder') (有效)或任何类似的解决方案,因为我会将文件传输到另一台计算机。 I use python 3.8.4.我使用 python 3.8.4。 How can I import from different files?如何从不同的文件导入?

My test files:我的测试文件:

Python Modules
    - ModulesImport
        -  main.py
    - TestFile
        - mymodule.py

When importing modules in VSCode, VSCode searches for modules from the parent folder by default.在 VSCode 中导入模块时,VSCode 默认从父文件夹中搜索模块。 so if they are not the same parent folder, VSCode cannot automatically find the modules that need to be imported.所以如果它们不是同一个父文件夹,VSCode 无法自动找到需要导入的模块。

If you don't want to change the added folder path(' datapath_folder '), it is recommended that you add the following code to the beginning of the file.如果不想更改添加的文件夹路径(' datapath_folder '),建议在文件开头添加如下代码。 It adds the file that needs to be imported to the system path so that VSCode can find it.它将需要导入的文件添加到系统路径中,以便 VSCode 可以找到它。 (It does not need to change any folder path) (不需要更改任何文件夹路径)

 import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

在此处输入图片说明

Update:更新:

If importing classes in other scripts, we can use " . " to indicate the files and folders of the class: (The above statement can also be used.)如果在其他脚本中导入类,我们可以用“ . ”来表示类的文件和文件夹:(也可以用上面的语句。)

在此处输入图片说明

(class: class_aa in main.py ) (类: class_aa中的main.py

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

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