【问题标题】:Formatting a command in python在python中格式化命令
【发布时间】:2015-03-26 00:48:51
【问题描述】:

我能够通过命令行运行此命令,但是当我将它转移到 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 解决

【问题讨论】:

  • 默认情况下subprocess.call 具有shell=False。您需要通过 shell 调用它,因此请使用 subprocess.call(test, 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 的清晰说明,我会记住这个提示以备后用。谢谢!

标签: python-2.7 amazon-web-services amazon-ec2 subprocess


【解决方案1】:

如果您的 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)

也就是说,您的代码中至少存在两个问题:

  1. 转义序列,例如\r\t as pointed out by @dgsleeps
  2. > 是一个 shell 重定向运算符,即,您需要运行 shell 或在 Python 中模拟它

【讨论】:

  • 哇,这符合我的需要。谢谢!
【解决方案2】:

字符“\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

【讨论】:

  • 我明白了,但遗憾的是它仍然给我同样的错误。除了您的回答之外,我还尝试将“\\”作为转义(?)字符添加到文件路径中,但仍然没有变化。
猜你喜欢
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多