Skip to main content
 首页 » 编程设计

python之无法将变量传递给python中的bash命令

2024年11月24日7Terrylee

我正在尝试像这样将 python 变量传递给 bash 命令:

subscriptionId = "xxxxx" 
command = " az account show -s $subscriptionId" 
subprocess.check_output(command) 

出现以下错误:

error : az account show: error: argument --subscription/-s: expected one argument 

请您参考如下方法:

分配像 subscriptionId = "xxxxx" 这样的 Python 变量并不能神奇地将它放置在您的环境中,更不用说将它传递给子进程了。您需要自己进行插值:

command = f"az account show -s {subscriptionId}" 

如果您真的想要使用环境变量,请添加您想要的变量并启用 shell 扩展:

subscriptionId = ... 
env = os.environ.copy() 
env['subscriptionId'] = subscriptionId 
command = "az account show -s ${subscriptionId}" 
subprocess.check_output(command, env=env, shell=True) 

或者,您可以弄乱自己的进程环境:

subscriptionId = ... 
os.environ['subscriptionId'] = subscriptionId 
command = "az account show -s ${subscriptionId}" 
subprocess.check_output(command, shell=True) 

在我看来,不建议使用这些选项,因为它们会引发 shell=True 带来的所有安全问题,同时不会为您提供真正的优势。