Python 在subprocess.run中使用变量
我正在尝试使用Python 在subprocess.run中使用变量,python,subprocess,Python,Subprocess,我正在尝试使用subprocess.run在python中运行Linux curl命令 此代码在命令行中运行良好: curl -F file=@$filename -F "initial_comment=$logo detected" -F channels=test -H "Authorization: Bearer xoxp-1638450445057-1631984334692-2039667356465-c7687a36843591bd232ac7b641e
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)HTTP2帧层中的错误
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通过列表而不是引用分隔的项目
运行([“curl”、“-F”、F“file=@{filename}”、“-F”、F“initial_comment={logo_detected}”、…]))
#^插入变量的字符串格式
在特定环境中引用环境变量时,请使用
os.environ
访问它们:
filename,logo\u detected=os.environ[“filename”],os.environ[“logo\u detected”]
运行([“curl”、“-F”、F“file=@{filename}”、“-F”、F“initial_comment={logo_detected}”、…]))
在使用shell=False
时,不需要转义空格,在使用shell=True
时,也不需要分隔参数在命令上运行时,命令的输出是什么Line@Sagar在命令上运行时,它是一个json输出line@mousetail我不明白你的意思。我的subprocess.run命令有什么问题吗?我从中得到一个KeyError。@user15838691请记住,我只是在猜测bash代码引用的变量类型。当os.environ
给出一个keyrerror时,这意味着您不打算使用环境变量,而是忘记了在Python中声明它们,应该直接使用它,或者您确实打算使用环境变量,但忘记在父程序中声明它们–例如,通过bash中的导出文件名
。文件名和logo_检测到包含用Python声明的字符串。我正在尝试将这两个变量传递给subprocess.run命令。然后不要使用…=os.environ…
位。在这种情况下,运行命令subprocess.run([“curl”,“-F”,F“file=@{filename}”,“-F”,F“initial_comment={logo_detected}”,…])
可以工作,但我得到一个错误:curl:(92)HTTP/2流0没有完全关闭:协议错误(err 1)(对不起,我是新手)