简体   繁体   English

如何在 python 脚本上运行高级 Linux 命令

[英]How to run advance Linux command on python script

I want to get the string output of the following linux command我想获取以下 linux 命令的字符串 output

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

I tried with我试过了

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

but the output is, output = subprocess.check_output("systemctl show node_exporter |grep LoadState| awk '{split($0,a,"="); print a[2]}'", shell=True) SyntaxError: keyword can't be an expression but the output is, output = subprocess.check_output("systemctl show node_exporter |grep LoadState| awk '{split($0,a,"="); print a[2]}'", shell=True) SyntaxError: keyword can不是表达

You need to escape the double quotes (because they indicate the begin/end of the string):您需要转义双引号(因为它们指示字符串的开始/结束):

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

Well,出色地,

First of all, the function takes a list of strings as a command, not a single string.首先,function 将字符串列表作为命令,而不是单个字符串。 Eg:例如:

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

Secondly.第二。 If the linux command is super complex or contains lots of lines - it makes sense to create a separate bash file eg command.sh, put your linux commands there and run the script from python with: If the linux command is super complex or contains lots of lines - it makes sense to create a separate bash file eg command.sh, put your linux commands there and run the script from python with:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM