You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Bash脚本转Python2.7脚本后执行报错‘repo command not found’求助

解决Python脚本中执行repo命令提示"command not found"的问题

问题根源

你遇到的问题核心在于:每个os.system()调用都会启动一个独立的子Shell进程,这些进程之间的环境变量是完全隔离的。

比如你最初的代码:

os.system("source /proj/common/tools/repo/etc/profile.d/repo.sh")
os.system("repo project init " + branch)

第一个source命令确实在它自己的子Shell里加载了repo.sh的环境变量(比如把repo的路径加入PATH),但这个子Shell执行完就退出了,环境变量不会传递给下一个os.system()启动的新Shell,所以第二个命令找不到repo。


解决方案1:将所有命令放在同一个Shell会话中执行

最简单的办法是把所有需要连续执行的命令整合成一个字符串,用bash -c在同一个Shell里执行,这样环境变量就能持续生效:

import os

# 替换成你的实际branch和image变量
branch = "your-branch-name"
image = "your-image-name"

# 用&&连接命令,确保前一个命令成功才执行下一个
full_cmd = """
source /proj/common/tools/repo/etc/profile.d/repo.sh && \
repo project init {} && \
repo project sync && \
source poky/fnc-init-build-env build && \
bitbake -g {}
""".format(branch, image)

# 用bash执行整个命令串
os.system("bash -c '{}'".format(full_cmd))

这里用\来换行保持代码可读性,&&保证只有前序命令执行成功时才会继续下一步,避免失败后继续执行无意义的命令。


解决方案2:用subprocess模块管理环境变量(更推荐)

os.system是比较老旧的API,Python官方更推荐使用subprocess模块,它能更精细地控制进程的环境变量、输出捕获等。

我们可以先执行source命令并导出更新后的环境变量,然后把这个环境传给后续的所有命令:

import subprocess
import os

branch = "your-branch-name"
image = "your-image-name"

# 复制当前环境变量,作为基础环境
current_env = os.environ.copy()

# 执行source repo.sh并获取更新后的环境变量
source_repo_cmd = "source /proj/common/tools/repo/etc/profile.d/repo.sh && env"
env_output = subprocess.check_output(
    source_repo_cmd,
    shell=True,
    executable="/bin/bash",
    env=current_env
)

# 解析输出,更新环境变量字典
for line in env_output.splitlines():
    line_str = line.decode("utf-8")
    if "=" in line_str:
        key, value = line_str.split("=", 1)
        current_env[key] = value

# 执行repo init和sync,使用更新后的环境
subprocess.check_call(
    f"repo project init {branch}",
    shell=True,
    executable="/bin/bash",
    env=current_env
)
subprocess.check_call(
    "repo project sync",
    shell=True,
    executable="/bin/bash",
    env=current_env
)

# 执行source poky的脚本,再次更新环境
source_poky_cmd = "source poky/fnc-init-build-env build && env"
poky_env_output = subprocess.check_output(
    source_poky_cmd,
    shell=True,
    executable="/bin/bash",
    env=current_env
)
for line in poky_env_output.splitlines():
    line_str = line.decode("utf-8")
    if "=" in line_str:
        key, value = line_str.split("=", 1)
        current_env[key] = value

# 最后执行bitbake
subprocess.check_call(
    f"bitbake -g {image}",
    shell=True,
    executable="/bin/bash",
    env=current_env
)

这种方式的优势是:

  • 可以逐个控制每个命令的执行逻辑,比如捕获输出、处理错误
  • 环境变量的变化可以被精确跟踪和传递

额外提示

  • 一定要指定executable="/bin/bash",因为source是Bash的内置命令,默认的sh可能不支持这个语法
  • 如果你用的是Python 3.6+,可以用f-string来格式化命令,比.format()更简洁

内容的提问来源于stack exchange,提问作者sabarish s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:18:36