在python中格式化命令



我可以通过命令行运行此命令,但当我将其转移到Python脚本并运行时,它不起作用。

test = 'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot > "V:rwongWork FilesPythontest.txt"'
subprocess.call(test)

我得到一个错误,它说"返回非零退出状态255"。是因为我格式化字符串的方式吗?总的来说,我有什么选择可以让它发挥作用?

编辑:它已经由J.F.Sebastian 解决

如果在Windows机器的%PATH%中有aws.exe,则将其输出保存在给定文件中:

#!/usr/bin/env python
import subprocess
cmd = ('aws ec2 create-image --instance-id i-563b6379 '
       '--name rwong_TestInstance --output text '
       '--description rwong_TestInstance --no-reboot')
with open(r"V:rwongWork FilesPythontest.txt", 'wb', 0) as file:
    subprocess.check_call(cmd, stdout=file)

即,您的代码中至少有两个问题:

  1. 如@dgsleeves所指出的rt等转义序列
  2. >是一个shell重定向操作符,即您需要运行shell或在Python中模拟它

字符"\r"作为盒带返回,"\t"作为制表符;使用原始输入,在单引号前加上"r";看看这个:

>>> test = 'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot > "V:rwongWork FilesPythontest.txt"'
>>> len(test)
172
>>> test2 = r'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot > "V:rwongWork FilesPythontest.txt"'
>>> len(test2)
174

最新更新