Python: How do I save something that printed in a terminal as a variable to compare later?

StackOverflow https://stackoverflow.com/questions/5300134

  •  22-10-2019
  •  | 
  •  

سؤال

import imaplib
import pprint

IMAP_SERVER='imap.gmail.com'
IMAP_PORT=993

M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
rc, resp = M.login('user@gmail.com', 'password')
print rc, resp

M.select()
for msg_num in M.search(None, "UNDELETED")[1][0].split():
    msg = M.fetch('1', '(BODY.PEEK[TEXT])') 
    print msg[1][0][1][139:161]

M.close()         
M.logout()

I'm a new beginner in python programming and the above python code is one that I'm using for a program I want to do. When I run this in a terminal I get the response that I have authenticated my account and then it displays the message between characters 139 & 161, which is the following in the example email:

This is just a test...

This is printed out in the terminal. What I want to do is take this printout and compare it to something else. For example: if a=b then x. What I want to do is that if the statement is true to send a signal to the serial port.

Any help is appreciated and anticipated thanks to all that help...

هل كانت مفيدة؟

المحلول

Simply assign the message to a variable before you print it:

for msg_num in M.search(None, "UNDELETED")[1][0].split():
    msg = M.fetch('1', '(BODY.PEEK[TEXT])') 
    a = msg[1][0][1][139:161]
    print a

# later..
if a == 'this is just a test...':
   # your code here
   pass

Obviously, you should use a more meaningful variable name than "a".

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top