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

相关推荐
钅日 勿 XiName1 天前
一小时速通Pytorch之自动梯度(Autograd)和计算图(Computational Graph)(二)
人工智能·pytorch·python
故林丶1 天前
【Django】Django笔记
python·django
IT北辰1 天前
Python实现居民供暖中暖气能耗数据可视化分析(文中含源码)
开发语言·python·信息可视化
FreeCode1 天前
LangChain1.0智能体开发:长期记忆
python·langchain·agent
Predestination王瀞潞1 天前
Python __name__ 与 __main__
开发语言·python
萧曵 丶1 天前
Python 字符串、列表、元组、字典、集合常用函数
开发语言·前端·python
梦想的初衷~1 天前
Plaxis自动化建模与Python应用全解:从环境搭建到高级案例实战
python·自动化·工程设计·工程软件
Q_Q5110082851 天前
python+uniapp基于微信小程序的垃圾分类信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
HackerTom1 天前
vs code jupyter连gpu结点kernel
python·jupyter·gpu·vs code·远程
weixin_468466851 天前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题