如何在 python 脚本中的 bash 脚本中使用 python 变量

how to use python variables in bash script inside python script

我正在尝试在 python 脚本中的 bash 脚本中使用我的 python 变量,如下所示...

import os
import submodule
URL="http://wmqa.blob.core.windows.net..."
os.system(subprocess.call("curl -I --silent GET ",str(URL), "| awk '/x-ms-copy-status/ {print}'"))

# I also tried with 

os.system(subprocess.call("curl -I --silent GET "+URL+ "| awk '/x-ms-copy-status/ {print}'"))

如何在 curl 中的 GET 之后传递 URL 我还需要在 curl 之后执行一些额外的命令来获取状态

对于初学者来说,最好不要使用 os.system。它很久以前就被替换了(实际上是 19 年前;在 PEP 324 中)。要回答您的问题,您可以使用 f-strings 或 python 中字符串中允许的任何其他格式来引用变量。这是一个例子。

import subprocess

my_var = "hello from my shell"
subprocess.Popen(f"echo {my_var}", shell=True).wait()

其中,当 运行 时,输出:

➜ ./main.py 
hello from my shell

下面是一个可能更接近您的配置的示例:

import subprocess

url = "http://echo.jsontest.com/var"
my_var = "hello"
subprocess.Popen(f"curl -s {url}/{my_var} | jq .var", shell=True).wait()

输出:

➜ ./main.py
"hello"