如何从根目录和子目录运行Python

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

在具有多个独立模块的 Python 存储库中,我希望能够在子目录中单独运行它们,以及从根目录中的运行文件连接它们。

示例回购树:

/
├── SPS
│   ├── __init__.py
│   ├── SPS_run.py
│   └── components
│       ├── __init__.py
│       ├── comp1.py
│       └── comp2.py
├── Testing
│   ├── __init__.py
│   ├── Test_run.py
│   └── components
│       ├── __init__.py
│       ├── comp3.py
│       └── comp4.py
└── main_run.py

问题在于导入本地模块,以便它们可以在 main_run.py、Test_run.py 和 SPS_run.py 中运行。

我对其进行了设置,以便 main_run.py 可以与相对于 root 的导入一起使用。

从 Test_run.py 和 SPS_run.py 中,我尝试像这样更改目录,但没有成功:

# Get the directory of the script
current_script_directory = os.path.dirname(os.path.abspath(__file__))

# Get the parent directory of the current script directory
parent_directory = os.path.dirname(current_script_directory)

# Change the current working directory to the parent directory
os.chdir(parent_directory)
python-3.x python-import
1个回答
0
投票

更改 Test_run.py 和 SPS_run.py 中的系统路径有效:

# Get the directory of the script
current_script_directory = os.path.dirname(os.path.abspath(__file__))

# Get the root directory of the project
root_directory = os.path.dirname(current_script_directory)

# Add the root directory to sys.path
if root_directory not in sys.path:
    sys.path.append(root_directory)
© www.soinside.com 2019 - 2024. All rights reserved.