Python 2.7 用python格式化命令

Python 2.7 用python格式化命令,python-2.7,amazon-web-services,amazon-ec2,subprocess,Python 2.7,Amazon Web Services,Amazon Ec2,Subprocess,我可以通过命令行运行这个命令,但是当我将它转换到Python脚本并运行它时,它就不起作用了 test = 'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot > "V:\rwong\Work Files\Python\test.txt"' subprocess.call(t

我可以通过命令行运行这个命令,但是当我将它转换到Python脚本并运行它时,它就不起作用了

test = 'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot > "V:\rwong\Work Files\Python\test.txt"'
subprocess.call(test)
我得到一个错误,它显示返回的非零退出状态255。是因为我格式化字符串的方式吗?总的来说,我有什么办法让它发挥作用


编辑:J.F.Sebastian已解决此问题

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

>>> test = 'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot > "V:\rwong\Work Files\Python\test.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:\rwong\Work Files\Python\test.txt"'
>>> len(test2)
174
如果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:\rwong\Work Files\Python\test.txt", 'wb', 0) as file:
    subprocess.check_call(cmd, stdout=file)
i、 例如,代码中至少有两个问题:

转义序列,例如\r\t >是一个shell重定向操作符,即您需要运行shell或在Python中模拟它
默认情况下,subprocess.call的shell=False。您需要通过shell调用它,所以使用subprocess.calltest,shell=True。顺便说一句,dgsleeps关于转义字符的回答也是正确的。我曾考虑过使用shell=True,但我认为如果使用命令的任何用户生成部分,使用shell=True会带来一些安全风险。如果要在不使用shell的情况下调用它,则必须将shell命令转换为参数列表。例如,这个subprocess.call'ls-l',shell=True将变成subprocess.call['ls','-l'],shell=False。您必须这样做,因为当您使用shell=True时,正是shell为您分隔了参数。好的,感谢您在shell=True上提供了清晰的说明,稍后我将记住这个技巧。非常感谢。我明白了,但遗憾的是,它仍然给了我同样的错误。除了您的答案,我还尝试将\\作为转义字符添加到文件路径中,但仍然没有更改。哇,这是我需要的解决方法。非常感谢。