Python 在终端中设置类似 Intellij 的工作目录

问题描述 投票:0回答:1

我有一个Python,它具有以下文件夹/文件结构。

Project/
-- generic_module
-- directory
---- sub_directory
------ main.py (uses generic_module, & other imports are relative to Project)

现在,如果我想通过 Intellij IDE 运行 main.py,我只需在运行配置中设置“工作目录”即可正常工作。

我想在没有 Intellij IDE 的情况下通过终端运行它。这种情况我该怎么办?

我尝试了 Project/ 文件夹中的“python directory/sub_directory/main.py”等内容,但仍然面临导入错误。

python intellij-idea python-import
1个回答
0
投票

IntelliJ IDE 在幕后更改了 pythonpath 环境变量。 因此,通过终端运行 python 脚本可以通过两种方式完成

Powershell /(任何其他 shell)

$env:PYTHONPATH+=";<path_of_directories_containing_the_imports>

Pythonic 方式感谢 Tim Roberts 的评论

sys.path.append(...)

os.abspath(os.dirname(__file__)+"../..")
© www.soinside.com 2019 - 2024. All rights reserved.