如何在Python中source Shell环境文件并获取使用其中变量
Got it, let's fix this issue for you. The problem you're facing is that when you run source via a Python subprocess, it executes in a child shell process—and those environment variables don't get passed back to your parent Python process. Here are two reliable solutions to get your FLAG and TAG variables into your script:
Solution 1: Parse the Environment File Directly
This is my go-to method because it avoids spawning extra shell processes and works perfectly for simple export-only env files like yours. We'll read the file line by line, extract the variables, and add them to Python's runtime environment.
import os def load_env_file(env_file_path): with open(env_file_path, 'r') as f: for line in f: # Skip empty lines and comments stripped_line = line.strip() if not stripped_line or stripped_line.startswith('#'): continue # Remove the "export " prefix if present if stripped_line.startswith('export '): stripped_line = stripped_line[7:] # Split variable name and value (handles values with = signs too) if '=' in stripped_line: var_name, var_value = stripped_line.split('=', 1) # Strip any surrounding quotes from the value var_value = var_value.strip('\'"') # Add to the current Python process's environment os.environ[var_name] = var_value # Load your environment file (replace with your actual file path) load_env_file('/path/to/env_var.env') # Now you can access and use the variables print(f"FLAG value: {os.environ.get('FLAG')}") print(f"TAG value: {os.environ.get('TAG')}") # Example usage in your script if os.environ.get('FLAG') == 'YES': print("Flag is set to YES, running targeted logic...")
Solution 2: Use a Shell Subprocess to Export Variables
If your environment file has complex shell logic (not just export statements), this method works by having the shell source the file, then output all environment variables, which we then parse into Python's environment.
import os import subprocess def load_env_via_shell(env_file_path): # Run a shell command: source the file, then print all environment variables cmd = f"source {env_file_path} && env" # Capture the output from the shell command result = subprocess.run( cmd, shell=True, capture_output=True, text=True, check=True # Throws an error if the command fails (e.g., file not found) ) # Parse each line of the output into environment variables for line in result.stdout.splitlines(): if '=' in line: var_name, var_value = line.split('=', 1) os.environ[var_name] = var_value # Load your environment file load_env_via_shell('/path/to/env_var.env') # Access the variables print(f"FLAG: {os.environ['FLAG']}") print(f"TAG: {os.environ['TAG']}")
⚠️ Note: Using shell=True can pose a security risk if env_file_path comes from untrusted input (it could allow shell injection attacks). Stick with Solution 1 if your env file only has simple export lines.
Why Your Initial Approach Didn't Work
When you run source via subprocess, it runs in a child shell. Environment variables are only available to the process they're set in and its direct children—they don't bubble back up to the parent process (your Python script). The solutions above either bypass the shell entirely or capture the variables from the child shell before it exits.
内容的提问来源于stack exchange,提问作者AbhinavVaidya8

