如何解决将 Windows cmd 传递给 Python 子进程
我正在尝试使用 Pyton 的子进程执行 aws cli 命令
windows cmd:
aws --profile some_profile --region some_region ec2 describe-instances --filters Name=tag:some_tag,Values=some_value --query "Reservations[*].Instances[*].{AvailabilityZone:Placement.AvailabilityZone,Status:State.Name,Name:Tags[?Key=='Name']|[0].Value}" --output=table
这就是我尝试这样做的方式:
profile = "some_profile"
region = "some_region"
ec2_filters = "Name=tag:some_tag,Values=some_value"
ec2_query = "Reservations[*].Instances[*].{AvailabilityZone:Placement.AvailabilityZone,Name:Tags[?Key=='Name']|[0].Value}"
ec2_output_type = "table"
proc = subprocess.Popen(["aws","--profile",profile,"--region",region,"ec2","describe-instances","--filters",ec2_filters,"--query",ec2_query,"--output",ec2_output_type],stdout=subprocess.PIPE,shell=True)
这是错误信息:
'[0].Value}' 未被识别为内部或外部命令, 可运行的程序或批处理文件。
解决方法
我没有安装 aws,所以我创建了一个模拟批处理文件来回吐它收到的内容。我确实尝试过我最初的猜测,你是对的,这通常很困难,但我想通了。很抱歉没有测试我让您尝试的内容。
无论如何,aws.bat
包含一行,echo %*
,它打印回批处理文件作为参数接收的任何内容,因此我们知道它正在工作。
然后,我尝试使用您的命令。我遇到了与您相同的错误,因此我将其修改为:
.\aws.bat --profile some_profile --region some_region ec2 describe-instances --filters Name=tag:some_tag,Values=some_value --query '"Reservations[*].Instances[*].{AvailabilityZone:Placement.AvailabilityZone,Status:State.Name,Name:Tags[?Key=='Name']|[0].Value}"' --output=table
这输出了命令,这意味着它被正确执行了。
然后,我修改了您的代码以确保所有查询都包含引号。我使用简单的字符串连接来做到这一点。
import subprocess
profile = "some_profile"
region = "some_region"
ec2_filters = "Name=tag:some_tag,Values=some_value"
ec2_query = (
'"Reservations[*].Instances[*].{AvailabilityZone:Placement.AvailabilityZone,Name:Tags[?Key=='
"'Name'"
']|[0].Value}"'
)
ec2_output_type = "table"
proc = subprocess.Popen(["aws.bat","--profile",profile,"--region",region,"ec2","describe-instances","--filters",ec2_filters,"--query",ec2_query,"--output",ec2_output_type])
这奏效了。有趣的是,如果我以非正统的方式使用三重引号,它也会起作用。
ec2_query = ' '''"Reservations[*].Instances[*].{AvailabilityZone:Placement.AvailabilityZone,Name:Tags[?Key=='Name']|[0].Value}"' '''
注意开头,' '''"
。我真的不知道发生了什么。
无论如何,更简单的解决方案是拆分您的字符串,以免引号引起混淆。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。