【发布时间】:2015-05-29 08:08:39
【问题描述】:
我正在尝试使用 Python 脚本和 Windows 任务计划程序在 EC2 上自动创建 Windows 映像。到目前为止,我将此作为我的工作基线代码。
awsstring1 = 'aws ec2 create-image --instance-id i-49a0a7b3 --name "Node.Js.ServerTest " --output text --description "Node.Js.ServerTest" --no-reboot'
subprocess.call(awsstring1)
现在我想在描述和名称中附加日期和时间作为附加信息。见下文
datestring = time.strftime("%c")
awsstring1 = 'aws ec2 create-image --instance-id i-49a0a7b3 --name "Node.Js.ServerTest %s" --output text --description "Node.Js.ServerTest %s" --no-reboot' %(datestring, datestring))
subprocess.call(awsstring1)
现在代码运行没有错误,但它没有创建图像。是因为我创建awsstring1 的方式吗?如果是这样,是否有解决方法?
另外,有没有办法在运行subprocess.call 命令后获得输出?例如,我想捕获
subprocess.call('ls -a')
编辑: 当运行下面的代码时,它应该有一个创建图像的输出。
awsstring1 = 'aws ec2 create-image --instance-id i-9bedb4b4 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot'
subprocess.call(awsstring1)
输出:
{
"ImageId": "ami-5731123e"
}
我需要那个 ami-5731123e 部分。如果有办法将其发送到文本文件,那就太好了。当我需要运行类似的命令来获取 IP 地址时,获取输出也会对我有所帮助。
Edit2:我已编写此代码用于将输出保存到文本文件,但我收到“返回非零退出状态 255”的错误 此不带开头 ' 和 end ' 的命令将在命令行上运行。是否有关于如何格式化这样的字符串以使用 subprocess.check_call 执行的指南?
test = 'aws ec2 create-image --instance-id i-563b6379 --name "rwong_TestInstance" --output text --description "rwong_TestInstance" --no-reboot'
test2 = r' > "V:\rwong\Work Files\Python\test.txt"'
subprocess.check_call(test + test2)
【问题讨论】:
-
您提到您正在通过“Windows 任务计划程序”执行此操作,但随后给出了运行
ls -a的示例,这不是 Windows 命令。你是在windows平台上做的吗? -
抱歉这个不好的例子。我更改了上面的帖子以反映我运行 subprocess.call 的目标。
-
如果不使用不安全的
shell=True,您绝对不能进行文件重定向。 -
所以无论我走到哪里,它看起来都像死路一条?
-
如果你使用
check_output,就像我在下面的回答中提到的那样,你可以将输出捕获到一个字符串,然后使用python使用标准io函数将它写入一个文件。
标签: windows python-2.7 amazon-web-services amazon-ec2 subprocess