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

相关推荐
yz1.29 分钟前
[sklearn] 特征工程
python·机器学习·sklearn
hello_ejb32 小时前
聊聊Spring AI Alibaba的SentenceSplitter
人工智能·python·spring
新辞旧梦3 小时前
企业微信自建消息推送应用
服务器·python·企业微信
虎头金猫3 小时前
如何解决 403 错误:请求被拒绝,无法连接到服务器
运维·服务器·python·ubuntu·chatgpt·centos·bug
dqsh066 小时前
树莓派5+Ubuntu24.04 LTS串口通信 保姆级教程
人工智能·python·物联网·ubuntu·机器人
sunshineine8 小时前
jupyter notebook运行简单程序
linux·windows·python
方博士AI机器人8 小时前
Python 3.x 内置装饰器 (4) - @dataclass
开发语言·python
万能程序员-传康Kk8 小时前
中国邮政物流管理系统(Django+mysql)
python·mysql·django
Logintern098 小时前
【每天学习一点点】使用Python的pathlib模块分割文件路径
开发语言·python·学习
开开心心_Every8 小时前
手机隐私数据彻底删除工具:回收或弃用手机前防数据恢复
android·windows·python·搜索引擎·智能手机·pdf·音视频