【问题标题】:Coalesce terminal output strings into one string with Python使用 Python 将终端输出字符串合并为一个字符串
【发布时间】:2017-01-31 07:56:29
【问题描述】:

我正在尝试获取 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

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

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

编辑 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: 已添加答案。

【问题讨论】:

  • 是的,似乎不起作用。事实上,我尝试使用替换将所有长度的空格减少到一个。替换似乎没有帮助。
  • 它不工作。我尝试了repr,它确实使它成为一个字符串,但带有\n、\t 和所有这些。之后我尝试使用正则表达式替换 \n \t 但不起作用。
  • 是的。我已经更新了。
  • 相同的输出。没有变化。它怎么不替换字符?毕竟它是命令的输出字符串。
  • 打败了我。我必须在我的机器上测试它。也许是特殊编码?顺便说一句,python 2 还是 python 3?

标签: python shell selenium terminal command


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2012-05-13
    • 1970-01-01
    • 2013-09-15
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多