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

相关推荐
程序小武1 小时前
python编辑器如何选择?
后端·python
一叶知秋12111 小时前
UV管理python项目
python
AndrewHZ1 小时前
【图像处理入门】2. Python中OpenCV与Matplotlib的图像操作指南
图像处理·python·opencv·计算机视觉·matplotlib·图像操作
golitter.2 小时前
langchain学习 01
python·学习·langchain
一叶知秋12112 小时前
LangChain Prompts模块
python
量化金策3 小时前
截面动量策略思路
python
心软且酷丶3 小时前
leetcode:7. 整数反转(python3解法,数学相关算法题)
python·算法·leetcode
逾非时3 小时前
python:selenium爬取网站信息
开发语言·python·selenium
天才测试猿3 小时前
Selenium操作指南(全)
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
不学无术の码农4 小时前
《Effective Python》第六章 推导式和生成器——避免在推导式中使用超过两个控制子表达式
开发语言·python