Shell脚本和Python的工作路径

在Linux中,工作目录(Working Directory)是指当前进程执行时所处的目录路径。工作目录会影响文件路径的解析,相对路径是基于工作目录来确定的。

场景描述

假设在项目根目录 / 下运行一个位于子目录 /home/user/scripts 中的 Bash 脚本 script.sh,而该脚本中又调用了一个 Python 程序 program.py。我们需要分析脚本和 Python 程序的工作目录。


1. 运行 Bash 脚本时的工作目录

  • 当你从根目录 / 运行脚本时:

    bash 复制代码
    cd /
    /home/user/scripts/script.sh
    • 脚本 script.sh 的工作目录是 调用脚本时所在的目录 ,即 /(根目录)。
    • 即使脚本位于 /home/user/scripts,它的工作目录仍然是 /
  • 如果你先切换到脚本所在目录再运行脚本:

    bash 复制代码
    cd /home/user/scripts
    ./script.sh
    • 此时脚本的工作目录是 /home/user/scripts

2. 脚本中运行 Python 程序时的工作目录

  • script.sh 中调用 Python 程序 program.py

    bash 复制代码
    python3 /home/user/scripts/program.py
    • Python 程序的工作目录继承自调用它的 Bash 脚本。
    • 如果脚本的工作目录是 /,那么 Python 程序的工作目录也是 /
    • 如果脚本的工作目录是 /home/user/scripts,那么 Python 程序的工作目录也是 /home/user/scripts

3. 在脚本或 Python 程序中改变工作目录

  • 在 Bash 脚本中,可以使用 cd 命令改变工作目录:

    bash 复制代码
    cd /home/user/scripts
    python3 program.py
    • 此时 Python 程序的工作目录是 /home/user/scripts
  • 在 Python 程序中,可以使用 os.chdir() 改变工作目录:

    python 复制代码
    import os
    os.chdir("/home/user/scripts")
    • 这会将 Python 程序的工作目录改为 /home/user/scripts

4. 获取当前工作目录

  • 在 Bash 脚本中,可以使用 pwd 命令获取当前工作目录:

    bash 复制代码
    echo "Current directory: $(pwd)"
  • 在 Python 程序中,可以使用 os.getcwd() 获取当前工作目录:

    python 复制代码
    import os
    print("Current directory:", os.getcwd())

总结

  • Bash 脚本的工作目录:取决于调用脚本时所在的目录。
  • Python 程序的工作目录:继承自调用它的 Bash 脚本,除非在脚本或 Python 程序中显式更改。
  • 如果需要确保程序在特定目录下运行,可以在脚本或 Python 程序中显式切换工作目录。

例如:

bash 复制代码
#!/bin/bash
cd /home/user/scripts
python3 program.py

这样无论从哪个目录调用脚本,Python 程序的工作目录都会是 /home/user/scripts

相关推荐
2401_841495642 分钟前
【LeetCode刷题】杨辉三角
数据结构·python·算法·leetcode·杨辉三角·时间复杂度·空间复杂度
小白开始进步21 分钟前
OpenCV图像滤波:Python实战指南
人工智能·python·opencv
Aevget23 分钟前
Python开发利器PyCharm v2025.3全新发布——支持主动数据探索
开发语言·ide·python·pycharm
znhy_2323 分钟前
day44打卡
python
子夜江寒26 分钟前
PyTorch:基于MNIST的手写数字识别
pytorch·python·深度学习
island131426 分钟前
PyTorch 2.0 核心技术深度解析torch.compile 从原理到实践
人工智能·pytorch·python
yaoh.wang34 分钟前
力扣(LeetCode) 119: 杨辉三角 II - 解法思路
数据结构·python·算法·leetcode·面试·职场和发展·跳槽
invicinble37 分钟前
arthas
开发语言·python
liliangcsdn37 分钟前
如何在jupyter-lab显示http链接的图片
python·jupyter
lzjava20241 小时前
Python中的模块和包
linux·开发语言·python