繁体   English   中英

在 subprocess.run 中使用变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM