[英]using variables in subprocess.run
我正在嘗試使用subprocess.run
在 python 中運行 Linux curl 命令。
此代碼在命令行中完美運行:
curl -F file=@$filename -F "initial_comment=$logo detected" -F channels=test -H "Authorization: Bearer xoxp-1638450445057-1631984334692-2039667356465-c7687a36843591bd232ac7b641ef83c1" https://slack.com/api/files.upload
當我嘗試使用subprocess.run
在我的 python 腳本中運行它時,
subprocess.run(["curl", "-F", "file=$filename", "-F", "\"initial_comment=$logo_detected\"", "-F", "channels=test", "-H", "\"Authorization: Bearer xoxp-1638450445057-1631984334692-2039667356465-c7687a36843591bd232ac7b641ef83c1\"", "https://slack.com/api/files.upload"])
我收到一個錯誤:
Warning: setting file {filename} failed!
curl: (26) read function returned funny value
編輯:我也收到此錯誤: curl: (16) Error in the HTTP2 framing layer
。
Edit2:我也嘗試設置shell=True
但我得到了與上面相同的錯誤。
subprocess.run("curl -F file=@$filename -F \"initial_comment=meWATCH logo\" -F channels=test -H \"Authorization: Bearer xoxp-1638450445057-1631984334692-2039667356465-c7687a36843591bd232ac7b641ef83c1\" https://slack.com/api/files.upload", shell=True)
由於subprocess.run
由 Python 運行而沒有中間 shell,因此它不理解 shell 或其他語言的變量、插值或其他表示法。 使用 Python 變量,插值和符號:
# v items delimited via list instead of quoting
subprocess.run(["curl", "-F", f"file=@{filename}", "-F", f"initial_comment={logo_detected}", ...])
# ^ string formatting to insert variables
當具體引用環境變量時,使用os.environ
來訪問它們:
filename, logo_detected = os.environ["filename"], os.environ["logo_detected"]
subprocess.run(["curl", "-F", f"file=@{filename}", "-F", f"initial_comment={logo_detected}", ...])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.