簡體   English   中英

如何在 python 腳本上運行高級 Linux 命令

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

我想獲取以下 linux 命令的字符串 output

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)

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不是表達

您需要轉義雙引號(因為它們指示字符串的開始/結束):

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

出色地,

首先,function 將字符串列表作為命令,而不是單個字符串。 例如:

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

第二。 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