build_code build_code - 2 months ago 16
Bash Question

Coalesce terminal output strings into one string with Python

I am trying to fetch the output of the

command and send it to web-based WhatsApp. I am able to fetch the output from the
command, but when I send it to WhatsApp, the
output is outputted as separate lines/messages. How do I make them into one and send it as a single message? Thanks.

fortune_list = ["(?i)art","(?i)comp","(?i)cookie","(?i)drugs","(?i)education","(?i)ethnic","(?i)food"]

for i in range(len(fortune_list)):
cmd = ['fortune', fortune_list_reply[i]]
output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
print output

The output on the terminal (
print output

enter image description here

The ouput sent on WhatsApp as seperate messages.

enter image description here

Desired output as a single message.

enter image description here

Edit 1 : Using
: Coalesces the strings but with these characters. Using regex replace to replace the characters isn't working.

"XXXI:\n\tThe optimum committee has no members.\nXXXII:\n\tHiring consultants to conduct studies can be an excellent means of\n\tturning problems into gold -- your problems into their gold.\nXXXIII:\n\tFools rush in where incumbents fear to tread.\nXXXIV:\n\tThe process of competitively selecting contractors to perform work\n\tis based on a system of rewards and penalties, all distributed\n\trandomly.\nXXXV:\n\tThe weaker the data available upon which to base one's conclusion,\n\tthe greater the precision which should be quoted in order to give\n\tthe data authenticity.\n\t\t-- Norman Augustine\n"

Edit 2: Answer added.


To coalesce the output strings of terminal into one, split the output at new lines and store them in a list.

sentence = ""
cmd = ['fortune', fortune_list_reply[i]]
output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
output = output.split('\n')
for string in output:
    string = string.split("\t")                                     
    for substring in string:
        if len(substring) == 0:
            sentence = sentence + " " + substring