在 Python 脚本中的 bash 命令中使用三个不同的引号

Use three different quotation marks in a bash command in Python scripts

我想在 python 脚本中使用三个不同的引号,因为我想在另一台计算机上执行两行 python 命令。例如:

import commands
command = "ssh someothercomputer 'python -c `import psutil; print psutil.cpu_percent()`'"
output = commands.getstatusoutput(command)[1]

但是,反引号不被识别为引号。错误如下:

"Badly placed ()'s.\nArgument expected for the -c option\nusage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...\nTry `python -h' for more information."

我怎样才能让它工作?

您可以不使用反引号,而是转义内部引号,将它们放在 command 中。像这样:

command =  "ssh someothercomputer 'python -c \"import psutil; print psutil.cpu_percent()\"'"

使用 commands 执行此命令会产生所需的输出(另一台计算机上的当前 cpu 百分比)