Reputation: 87
Can someone tell me how to get the output of the following command using subprocess to a list please?
curl --silent -u username:password http://localhost:55672/api/queues | sed 's/,/\n/g' | grep '"name"\:' | tr -d "name:" | tr -d -d \"
Tried "subprocess.popen", "subprocess.call" and "subprocess.popen" but to no avail. Below is one example i tried.
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
The error that is thrown at me when the latter is run
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]bindo@test1:~/rbmq_test $
Please note that the command is working when it is run on the shell and generates an output in below format
line1
line2
line3
Please can someone help?
Upvotes: 1
Views: 5793
Reputation: 2094
Probably is late , but this can be useful:
import subprocess
# cmd contains shell command
cmd="curl --silent -u username:passwordhttp://localhost:55672/api/queues | sed 's/,/\n/g' | grep '"name"\:' | tr -d "name:" | tr -d -d \""
process = subprocess.Popen(cmd,shell=True,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# The output from your shell command
result=process.stdout.readlines()
if len(result) >= 1:
for line in result:
print(line.decode("utf-8"))
Upvotes: 1
Reputation: 5322
You are quoting around the "name" seems to be wrong.
You are closing the double quoted string, that's why you are getting an invalid syntax, nothing related to the command itself.
Try adding an escape character before the quotes around 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)
Or replacing the double quote with single ones, this way you don't conflict with the command string:
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)
Based on the command line you posted first it seems that you need the double quoted one in the grep, so you need to escape it:
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)
Upvotes: 0
Reputation: 633
Look like the command have a lot of forbidden characters you need to escape maybe you can try the following
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)
Upvotes: 0