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

相关推荐
木土雨成小小测试员2 分钟前
Python测试开发之后端一
开发语言·数据库·人工智能·python·django·sqlite
黎子越10 分钟前
python循环相关联系
开发语言·python·算法
小北方城市网33 分钟前
Spring Cloud Gateway 进阶实战:自定义过滤器、动态路由与全链路日志监控
spring boot·python·rabbitmq·java-rabbitmq·数据库架构
副露のmagic34 分钟前
更弱智的算法学习 day53
开发语言·python
Java程序员威哥36 分钟前
SpringBoot多环境配置实战:从基础用法到源码解析与生产避坑
java·开发语言·网络·spring boot·后端·python·spring
yayatiantian_202242 分钟前
Ubuntu 24.04 安装与配置 pyenv
linux·运维·python·ubuntu·pyenv
June bug1 小时前
【python基础】常见的数据结构的遍历
开发语言·数据结构·python
深蓝电商API1 小时前
Selenium Grid分布式执行爬虫任务
爬虫·python·selenium
Just right1 小时前
安装RAGAS遇到的问题
笔记·python