Essentially my goal is to save the output of my def function into a list that I can then save into a data frame. I was working with the function and realized that every time I changed the definition function, it would make the changes to one output at a time. Then I realize that for each output the function is calling itself over and over again. I think I have to call a variable outside of this function that can combine all the calls that the function outputs but I'm not sure how. Updated code with suggestion
def getEmails():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
result = service.users().messages().list(userId='me').execute()
messages = result.get('messages')
for msg in messages:
txt = service.users().messages().get(userId='me', id=msg['id']).execute()
m_id = msg['id'] # get id of individual message
try:
payload = txt['payload']
headers = payload['headers']
for d in headers:
if d['name'] == 'Subject':
subject = d['value']
if d['name'] == 'From':
sender = d['value']
if d['name'] == 'Date':
date = d['value']
parts = payload.get('parts')[0]
data = parts['body']['data']
data = data.replace("-"," ").replace("_","/")
decoded_data = base64.b64decode(data)
soup = BeautifulSoup(decoded_data , "lxml")
body = soup.body()
names = soup.body.findAll('p')
page = soup.find('p', text=re.compile('has been listed on ')).getText()
if page:
match = re.search(r'has been listed on ' '\\b\w \\b' ' ', str(page))
if match:
site = match.group()
else:
None
def Convert(string):
li = list(string.split())
return li
if sender == 'Cryptocurrency Alerting <[email protected]>':
site = site.replace("has been listed on ", "")
s = list(Convert((str(site))))
results = []
results.append(s)
print(results)
except:
pass
getEmails()
The output of this function looks like this
[['OKEX']]
[['OKEX']]
[['OKEX']]
[['Kucoin']]
[['Kucoin']]
[['Kucoin']]
[['Kucoin']]
[['Hotbit']]
I've tried
k = print(s, end="", flush = True)
which outputs
['Hotbit']['Hotbit']['OKEX']['OKEX']['OKEX']
However, this doesn't make it a list. I need a variable outside of this function so that it can take the output and put it inside a list.
CodePudding user response:
Assemble your results and return them from the function:
def getEmails():
results = []
# lots of code...
if sender == 'Cryptocurrency Alerting <[email protected]>':
site = site.replace("has been listed on ", "")
s = list(Convert((str(site))))
results.append(s)
return results
# retrieve the results
results = getEmails()