【问题标题】:How to run advance Linux command on python script如何在 python 脚本上运行高级 Linux 命令
【发布时间】:2020-03-18 09:27:59
【问题描述】:

我想得到下面linux命令的字符串输出

systemctl show node_exporter |grep LoadState| awk '{split($0,a,"="); print a[2]}'

我试过了

import subprocess
output = subprocess.check_output("systemctl show node_exporter |grep LoadState| awk '{split($0,a,"="); print a[2]}'", shell=True)

但输出是, output = subprocess.check_output("systemctl show node_exporter |grep LoadState| awk '{split($0,a,"="); print a[2]}'", shell=True) SyntaxError: 关键字不能是表达式

【问题讨论】:

  • 你有引号冲突 - a,"="); - 你需要在这里转义双引号,否则它们会关闭你的 Python 字符串

标签: python systemctl


【解决方案1】:

你需要转义双引号(因为它们表示字符串的开始/结束):

import subprocess
output = subprocess.check_output("systemctl show node_exporter |grep LoadState| awk '{split($0,a,\"=\"); print a[2]}'", shell=True)

【讨论】:

    【解决方案2】:

    嗯,

    首先,该函数将字符串列表作为命令,而不是单个字符串。例如:

    "ls -a -l" - wrong
    ["ls", "-a", "-l"] - good
    

    其次。如果 linux 命令非常复杂或包含很多行 - 创建一个单独的 bash 文件是有意义的,例如command.sh,将你的 linux 命令放在那里并从 python 运行脚本:

    import subprocess
    output = subprocess.check_output(["./command.sh"], shell=True)
    

    【讨论】:

    • 非常感谢您。因为我的命令有点复杂,所以我创建了一个 bash 文件并且它起作用了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2022-08-06
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多