使用Python将终端输出字符串合并为一个字符串

时间:2016-09-22 16:17:57

标签: python shell selenium terminal command

我正在尝试获取fortune命令的输出并将其发送到基于Web的WhatsApp。我可以从fortune命令获取输出,但是当我将其发送到WhatsApp时,fortune输出作为单独的行/消息输出。如何将它们组合成一个并将其作为单个消息发送?谢谢。

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

for i in range(len(fortune_list)):
    if re.search(re.compile(fortune_list[i]),reply):
        cmd = ['fortune', fortune_list_reply[i]]
        output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
        print output
        input_box[1].send_keys(output)
        time.sleep(1)
        b.find_element_by_class_name('send-container').click() 

终端上的输出(print output

enter image description here

在WhatsApp上发送的输出是单独的消息。

enter image description here

所需的输出作为单个消息。

enter image description here

编辑1: 使用repr:合并字符串,但使用这些字符。使用正则表达式替换以替换字符不起作用。

"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"

编辑2: 已添加答案。

1 个答案:

答案 0 :(得分:0)

要将终端的输出字符串合并为一个,请将输出拆分为新行并将其存储在列表中。

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:
            continue
        else:
            sentence = sentence + " " + substring