如何在Python脚本中运行.sh脚本并获取其中的路径与变量
当然有办法不用新建Python文件就能获取shell脚本里的变量!下面给你几个实用的方案:
方案1:让shell脚本输出变量,Python解析结果
核心思路是让shell执行你的脚本后,把需要的变量输出出来,再用Python解析这些输出。
假设你的shell脚本config.sh内容是这样的:
#!/bin/bash export PYTHON_PATH="/usr/local/lib/python3.8" export DATA_DIR="/var/data/my_project" export API_KEY="abc_123_xyz"
方法A:获取所有环境变量
如果想一次性拿到脚本里定义的所有环境变量,可以这样写Python代码:
import subprocess # 执行shell脚本并输出所有环境变量 result = subprocess.run( ['bash', '-c', 'source config.sh && env'], capture_output=True, text=True ) # 把输出解析成字典格式 env_vars = {} for line in result.stdout.splitlines(): if '=' in line: key, value = line.split('=', 1) env_vars[key] = value # 现在就能直接用这些变量了 print(env_vars['PYTHON_PATH']) print(env_vars['DATA_DIR'])
方法B:只获取指定变量
如果只需要特定几个变量,可以让shell直接输出这些变量,更高效:
import subprocess # 让shell输出指定变量,用分隔符分隔(这里用|,如果变量里可能有|就换个符号比如\0) result = subprocess.run( ['bash', '-c', 'source config.sh && echo "$PYTHON_PATH|$DATA_DIR|$API_KEY"'], capture_output=True, text=True ) # 分割结果得到变量值 python_path, data_dir, api_key = result.stdout.strip().split('|') print(python_path) print(api_key)
方案2:提取脚本中的变量定义单独执行
如果你的shell脚本里除了变量定义还有其他执行逻辑,不想运行那些逻辑,可以先提取出变量定义的行,再单独执行:
import subprocess # 读取shell脚本内容 with open('config.sh', 'r') as f: script_content = f.read() # 过滤出变量定义行(匹配export开头或直接VAR=xxx的行) var_defines = [] for line in script_content.splitlines(): stripped_line = line.strip() if stripped_line.startswith(('export ', '=')) or '=' in stripped_line: var_defines.append(stripped_line) # 把变量定义拼成命令执行,输出环境变量 cmd = f'bash -c "{ "; ".join(var_defines) } && env"' result = subprocess.run(cmd, capture_output=True, text=True, shell=True) # 解析成字典 env_vars = {} for line in result.stdout.splitlines(): if '=' in line: key, value = line.split('=', 1) env_vars[key] = value
注意事项
- 如果你的变量是通过动态命令生成的(比如
export DATA_DIR=$(pwd)/data),必须通过shell执行才能拿到正确值,直接解析文本会出错。 - 使用
shell=True时要注意安全,避免注入风险,如果脚本路径或变量是用户输入的,要格外谨慎。 - 如果变量包含空格、引号等特殊字符,建议用
shlex模块来处理分割,避免解析出错。
内容的提问来源于stack exchange,提问作者Saurabh Pandey
相关产品推荐
相关产品推荐

