Открытие файла Python, который импортирует из другого скрипта Python - PullRequest
0 голосов
/ 16 октября 2019

Я сделал две программы: gmailGetBig.py и guiHaroBig.py

В идеальном мире графический интерфейс пользователя вызывает основную часть программы gmail для одной из ее кнопок.

В режиме ожиданиядля python я использовал (import gmailGetBig) и затем вызывал gmailGetBig.main () в одном из методов. Это прекрасно работает только на холостом ходу. Когда я пытаюсь открыть графический интерфейс из командной строки, он ничего не делает.

Тем не менее, когда я закомментирую вызов gmailGetBig.py и закомментирую вызов, открываемый графическим интерфейсом при вызове из командной строки.

Я не уверен, что это из-за того, какЯ импортирую или вызываю другую программу или что-то еще.

Извините за многословный вопрос. Спасибо за вашу помощь.

РЕДАКТИРОВАТЬ: guiHaroBig:

from timeit import default_timer as timer
from tkinter import *
import re
import sys
import os
import gmailGetBig


key = []
temp = []
root = Tk()

root.title("HARO SEARCHER")

width=1700
height=900

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# calculate position x and y coordinates
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))


def func(event):
    print("You hit return")


def buttonClicked(event=NONE):
    word=entry1.get().lower()
    key.append(word)
    if box1.get(0,last=None)==key[0]:
        box1.insert(END, key[-1])
    else:
        box1.insert(END, *key)

##    text.insert(INSERT, test+"\n")
##    print(test)
    print(key)

    entry1.delete(0, 'end')

    print(len(key))


root.bind('<Return>', buttonClicked)

canvas1 = Canvas(root, width = 1500, height = 1000)
canvas1.config(bg='#DCEEF2')
canvas1.pack(fill = "both", expand = True)

label1 = Label(root,text = "Keywords")
label1.config(bg='#DCEEF2', fg = '#5A6C73', font=('Times New Roman', 18,))

label2 = Label(root,text = "Newsletter:")
label2.config(bg='#9BB9BF', fg='white', font=('helvetica', 12, 'bold'))

label3 = Label(root,text = "Keywords:")
label3.config(bg='#9BB9BF', fg='white', font=('helvetica', 12, 'bold'))

box1 = Listbox(root)
box1.config(cursor='cross', height = 30,width = 40,bg='#e0edee', fg='black', font=('times new roman', 13, 'bold'))
box1.yview()


def populateListbox():
    temp=key.copy()


def printListbox():
    box1.insert(END, *temp)


def callEmail():
    start = timer()
    gmailGetBig.main()

    end = timer()
    print(end-start)


def searchList():
    deleteResult()
    paras = []
    res = set()
    with open("result_HARRO.txt", 'rt') as f:
        text = f.read()
        offset = text.find("****************************")

        # we add 29 because we need to take out 28 '*'s + 1 '\n' character
        text = text[offset + 29:]

        paras = text.split('-----------------------------------')
        # print(paras[0])

    for item in key:   # default is zero
        print( item )
        # -35 because it takes out the "Back to Top Back to Category Index" part after each article segment
        # test = [i[:-35] for i in paras if item in i]

        for article in paras:
            ## if re.search(r'\b' + item + r'\b', str(article)):
            ## res.add( article[:-2] )

            articleText = article.lower()
            articleSplit = articleText
            if articleSplit.find(item)!=-1:
                res.add( article[:-2])

    with open("RESULT.txt","a") as j:
        print('--------------------------------'.join(res),file=j)

    os.startfile("RESULT.txt")


def deleteNewsletter():
    cleaner = open("result_HARRO.txt", "w")
    cleaner.close()


def deleteResult():
    restart= open("RESULT.txt","w")
    restart.close()


def clearListbox():
    box1.delete(0,END)
    del key[0:]
    print(key)


label1.place(relx =0.5, rely = .21999, anchor=("center"))
label2.place(relx = 0.68, rely = .29)
label3.place(relx =0.68, rely = .61)
box1.place(relx =0.5, rely = .6, anchor=("center"))

entry1 = Entry(root)
canvas1.create_window(850, 225, window=entry1)

button1 = Button(text= '---Click here to search---', command=searchList)
button1.configure(width = 50, bg='#5A6C73', fg='white', font=('helvetica', 12, 'bold')) 

canvas1.create_window(200,290, window=button1)
button1.place(x = 580,y = 855)

##button2 = Button(text= 'Reset documents', command=deleteResult)
##
##button2.configure(height = 1 ,width = 13, bg='red', fg='white', font=('helvetica', 12, 'bold')) 
##
##canvas1.create_window(200,275, window=button2)
##
##button2.place(x = 1, y = 100)

button3 = Button(text= 'Grab recent newsletter ', command=callEmail)
button3.configure(width = 18, bg='#5A6C73', fg='white', font=('arial', 12, 'bold')) 
canvas1.create_window(200,270, window=button3)
button3.place(relx = 0.77, rely = .29)

button4 = Button(text= 'Clear keys', command=clearListbox)
button4.configure(height = 1 ,width = 8, bg='#5A6C73', fg='white', font=('arial', 12, 'bold')) 
canvas1.create_window(200,270, window=button4)
button4.place(relx =0.77, rely = .64)

button5 = Button(text= 'Clear newsletter', command=deleteNewsletter)
button5.configure(height = 1 ,width = 12, bg='#5A6C73', fg='white', font=('helvetica', 12, 'bold')) 
canvas1.create_window(200,270, window=button5)
button5.place(relx = 0.77, rely = .35)

instru = open("About.txt","r")
about= instru.read()

text1 = Text(height = 30, width = 69)
text1.place(x = 38, y = 251)
text1.configure(state='normal', font = ('Times New Roman', 13))
text1.insert(INSERT, about)
text1.configure(state='disabled', wrap='word', cursor = 'none', bg = 'white', fg = "black")

labelText = Label(root)
labelText.place(x = 38, y = 211)
labelText.config(text="Instructions", font =( "Times New Roman",18), bg = "#DCEEF2", fg = '#5A6C73' )

labelTitle = Label(root)
labelTitle.place(relx = 0.45, rely = 0.1)
labelTitle.config(text="Haro Searcher", font =( "Times New Roman",20), bg = "#DCEEF2", fg = '#5A6C73' )

##var=IntVar()
##scale1 = Scale( root, from_=1, to=3,variable = var )
##scale1.place(x = 400, y = 250)
##
##
##buttonS = Button(root,text = "Select the number", command=sel)
##buttonS.place(x = 328, y = 360)
##
##labelS = Label(root)
##labelS.place(x = 328, y = 340)


def onselect(event):
    w = event.widget
    idx = int(w.curselection()[0])
    box1.delete(idx)
    key.pop(idx)
    print(key)


box1.bind('<<ListboxSelect>>', onselect)
root.mainloop()

gmailGetBig:

import datetime
import time
##import guiHaroBig
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import base64

from bs4 import BeautifulSoup
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
##k = guiHaroBig.var
##print(guiHaroBig.var)

def main():
##    ts = time.time()
##    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H-%M-%S')

    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json',
                SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', http=creds.authorize(Http()))

    # Call the Gmail API to fetch INBOX

    results = service.users().messages().list(userId='me',
            q='label:Haro', maxResults = 2).execute()
    messages = results.get('messages', [])
    print ("Total emails from Haro: ", str(len(messages)))
    if not messages:
        print ('No messages found.')
    else:
        print ('Message snippets:')
        for message in messages:
            message = service.users().messages().get(userId='me',
                    id=message['id'], format='full').execute()

            msg_str = message['payload']['parts'][0]['parts'][0]['body'
                    ]['data']
            clean_one = msg_str.replace('-', '+')  # decoding from Base64 to UTF-8
            clean_one = clean_one.replace('_', '/')
            clean_two = base64.b64decode(bytes(clean_one, 'UTF-8'))  # decoding from Base64 to UTF-8
            soup = BeautifulSoup(clean_two, 'lxml')

            mssg_body = soup.body()
            filename = "result_HARRO" + ".txt"

            jojo = open(filename, 'a')

            jojo.write (str((mssg_body)))

            jojo.close()

if __name__ == '__main__':
    main()

1 Ответ

0 голосов
/ 16 октября 2019

Мне удалось это исправить, включив другой скрипт (gmailGetBig.py) в создание графического интерфейса, добавив текстовые файлы или другие необходимые мне файлы.

Это мой файл спецификации:

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['guiHaroBig.py', 'gmailGetBig.py'],
             pathex=['C:\\Users\\AwesomeComputer\\Desktop\\Haro_distributable'],
             binaries=[],
             datas=[('*.txt','.'),('*.json','.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='guiHaroBig',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='guiHaroBig')
...