[英]How to get the command & arguments that was executed in shell with python
[英]How to get the final output of of shell command executed by python
我正在嘗試執行 shell 命令kubectl get ns | grep -E '(^|\s)namespace-test($|\s)'
kubectl get ns | grep -E '(^|\s)namespace-test($|\s)'
但無論是否有錯誤,我都會變得空虛。
我在錯誤和非錯誤情況下都變空的原因是它執行兩次命令(命令左右到|
),但我需要的是將實際輸出作為返回值,如果有一個,則說0
輸出,如果沒有輸出則為1
這就是我正在嘗試的:
get_ns_p1 = subprocess.Popen(['kubectl', 'get', 'ns'], stdout=subprocess.PIPE)
get_ns_p2 = subprocess.Popen(["grep", "-E", "\'(^|\s)"+NAMESPACE+"($|\s)\'"], stdin=get_ns_p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
get_ns_p1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out_ns, err = get_ns_p2.communicate()
print(out_ns)
有人能幫我嗎?
或者如果你對此有任何方法,這就是我想要做的......
我想執行一個有pipe
的 shell 命令並獲取輸出,如果有輸出,它應該返回一些值,如果輸出為空,它應該給出一個不同的值,如果有error
,它應該給出另一個不同的值輸出
我怎樣才能做到這一點?
首先,您必須通過管道拆分您的命令。 像這樣: [command for command in cmd.partition('|') if command != '|' if command != '']
[command for command in cmd.partition('|') if command != '|' if command != '']
之后,您必須啟動subprocess.Popen
命令。 第一次,執行列表中的第一項,之后你可以執行下一個元素,但你必須將上一次執行的結果傳遞給stdin
。 這將允許您執行管道命令。
但是,請小心shell=True
。 更多信息在這里。
示例代碼:
import logging
import subprocess # nosec
logging.basicConfig(filename='log.log',
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.INFO)
log = logging.getLogger(__name__)
def execute_and_create_output_from_cmd(cmd_parts):
"""
Functions executes cmd and adds parsed lines to <List> result.
:return: <List>
"""
try:
index = 0
process = {}
for cmd_part in cmd_parts:
cmd_part = cmd_part.strip()
if index == 0:
process[index] = subprocess.Popen(cmd_part, shell=True, # nosec
stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
process[index] = subprocess.Popen(cmd_part, shell=True, # nosec
stdin=process[index - 1].stdout, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
index += 1
(output, err) = process[index - 1].communicate()
exit_code = process[0].wait()
if exit_code != 0:
log.warning('Output: %s', output)
log.error('Error: %s', err)
log.error('Exit code: %s', exit_code)
else:
print(output) # do whatever you want with your output
except OSError as os_error:
log.error('Could not execute command: %s', os_error)
def split_cmd(cmd):
""" Split cmd command. Check if command contains '|'. '||' allowed. """
return [command for command in cmd.partition('|') if command != '|' if command != '']
if __name__ == '__main__':
cmd = split_cmd('ls -al | grep ibm')
execute_and_create_output_from_cmd(cmd)
我添加了logging
。 沒有必要。
[kchojnowski@zabbix4-worker1 ~]$ python test.py
drwxrwxr-x 2 kchojnowski kchojnowski 50 Jul 24 15:33 ibm_mq
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.