2017-07-19 58 views
0

有人可以告訴我如何使用子進程得到下面的命令的輸出到列表嗎?python子過程輸出到一個數組

curl --silent -u username:password http://localhost:55672/api/queues | sed 's/,/\n/g' | grep '"name"\:' | tr -d "name:" | tr -d -d \" 

試圖 「subprocess.popen」, 「subprocess.call」 和 「subprocess.popen」,但無濟於事。以下是我嘗試過的一個例子。

import json 
import subprocess 

HO=subprocess.check_output("curl --silent -u username:passwordhttp://localhost:55672/api/queues | sed 's/,/\n/g' | grep '"name"\:' | tr -d "name:" | tr -d -d \"", shell=True) 

print HO 

當後者運行

File "./rb.py", line 10 
    HO=subprocess.check_output("curl --silent -u username:password http://localhost:55672/api/queues | sed 's/,/\n/g' | grep '"name"\:' | tr -d "name:" | tr -d -d \"", shell=True) 
                                    ^
SyntaxError: invalid syntax 
[my_shell][email protected]:~/rbmq_test $ 

是我引發的錯誤,請注意,當它在shell中運行,並在下面的格式生成輸出命令正在

line1 
line2 
line3 

請問有人可以幫忙嗎?

回答

0

模樣的命令有很多,你需要逃避禁止字符也許你可以試試下面的

cmd = """ 
curl --silent -u username:password http://localhost:55672/api/queues | sed 's/,/\n/g' | grep '"name"\:' | tr -d "name:" | tr -d -d \" 
""" 
subprocess.check_output(cmd) 
+0

這需要在'check_output()'調用中'shell = True'。 – JohanL

+0

@Hamuel謝謝,但上述代碼沒有解決我的問題。 – bindo

0

您圍繞「名」引述似乎是錯誤的。

你正在關閉雙引號字符串,這就是爲什麼你得到一個無效的語法,與命令本身沒有任何關係。

嘗試在name左右的引號前添加轉義字符。

subprocess.check_output("curl --silent -u username:passwordhttp://localhost:55672/api/queues | sed 's/,/\n/g' | grep \"name\":' | tr -d \"name:\" | tr -d -d \"", shell=True) 

或更換單者雙引號,這樣你不命令字符串衝突:

subprocess.check_output("curl --silent -u username:passwordhttp://localhost:55672/api/queues | sed 's/,/\n/g' | grep 'name':' | tr -d 'name:' | tr -d -d \"", shell=True) 

根據您發佈第一個在命令行上看來,你需要雙引用grep中的一個,所以你需要逃避它:

subprocess.check_output("curl --silent -u username:passwordhttp://localhost:55672/api/queues | sed 's/,/\n/g' | grep '\"name\"':' | tr -d 'name:' | tr -d -d \"", shell=True) 
+0

謝謝,但不幸的是建議的選項仍然沒有運氣。 :( – bindo