Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';无法让python exe运行_Python_Exe - Fatal编程技术网

Can';无法让python exe运行

Can';无法让python exe运行,python,exe,Python,Exe,因此,我在将python 3.5脚本作为exe运行时遇到了问题。以下是我正在使用的代码: import base64 import imaplib import json import smtplib import urllib.parse import urllib.request from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import lxml.html GOOGL

因此,我在将python 3.5脚本作为exe运行时遇到了问题。以下是我正在使用的代码:

import base64
import imaplib
import json
import smtplib
import urllib.parse
import urllib.request
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import lxml.html

GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

GOOGLE_CLIENT_ID = '<FILL ME IN>'
GOOGLE_CLIENT_SECRET = '<FILL ME IN>'
GOOGLE_REFRESH_TOKEN = None


def command_to_url(command):
    return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command)


def url_escape(text):
    return urllib.parse.quote(text, safe='~-._')


def url_unescape(text):
    return urllib.parse.unquote(text)


def url_format_params(params):
    param_fragments = []
    for param in sorted(params.items(), key=lambda x: x[0]):
        param_fragments.append('%s=%s' % (param[0], url_escape(param[1])))
    return '&'.join(param_fragments)


def generate_permission_url(client_id, scope='https://mail.google.com/'):
    params = {}
    params['client_id'] = client_id
    params['redirect_uri'] = REDIRECT_URI
    params['scope'] = scope
    params['response_type'] = 'code'
    return '%s?%s' % (command_to_url('o/oauth2/auth'), url_format_params(params))


def call_authorize_tokens(client_id, client_secret, authorization_code):
    params = {}
    params['client_id'] = client_id
    params['client_secret'] = client_secret
    params['code'] = authorization_code
    params['redirect_uri'] = REDIRECT_URI
    params['grant_type'] = 'authorization_code'
    request_url = command_to_url('o/oauth2/token')
    response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8')
    return json.loads(response)


def call_refresh_token(client_id, client_secret, refresh_token):
    params = {}
    params['client_id'] = client_id
    params['client_secret'] = client_secret
    params['refresh_token'] = refresh_token
    params['grant_type'] = 'refresh_token'
    request_url = command_to_url('o/oauth2/token')
    response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8')
    return json.loads(response)


def generate_oauth2_string(username, access_token, as_base64=False):
    auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
    if as_base64:
        auth_string = base64.b64encode(auth_string.encode('ascii')).decode('ascii')
    return auth_string


def test_imap(user, auth_string):
    imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
    imap_conn.debug = 4
    imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
    imap_conn.select('INBOX')


def test_smpt(user, base64_auth_string):
    smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
    smtp_conn.set_debuglevel(True)
    smtp_conn.ehlo('test')
    smtp_conn.starttls()
    smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64_auth_string)


def get_authorization(google_client_id, google_client_secret):
    scope = "https://mail.google.com/"
    print('Navigate to the following URL to auth:', generate_permission_url(google_client_id, scope))
    authorization_code = input('Enter verification code: ')
    response = call_authorize_tokens(google_client_id, google_client_secret, authorization_code)
    return response['refresh_token'], response['access_token'], response['expires_in']


def refresh_authorization(google_client_id, google_client_secret, refresh_token):
    response = call_refresh_token(google_client_id, google_client_secret, refresh_token)
    return response['access_token'], response['expires_in']


def send_mail(fromaddr, toaddr, subject, message):
    access_token, expires_in = refresh_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN)
    auth_string = generate_oauth2_string(fromaddr, access_token, as_base64=True)

    msg = MIMEMultipart('related')
    msg['Subject'] = subject
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg.preamble = 'This is a multi-part message in MIME format.'
    msg_alternative = MIMEMultipart('alternative')
    msg.attach(msg_alternative)
    part_text = MIMEText(lxml.html.fromstring(message).text_content().encode('utf-8'), 'plain', _charset='utf-8')
    part_html = MIMEText(message.encode('utf-8'), 'html', _charset='utf-8')
    msg_alternative.attach(part_text)
    msg_alternative.attach(part_html)
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo(GOOGLE_CLIENT_ID)
    server.starttls()
    server.docmd('AUTH', 'XOAUTH2 ' + auth_string)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.quit()

def main():
    if GOOGLE_REFRESH_TOKEN is None:
        print('No refresh token found, obtaining one')
        refresh_token, access_token, expires_in = get_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
        print('Set the following as your GOOGLE_REFRESH_TOKEN:', refresh_token)
        exit()

    send_mail('--------@gmail.com', '--------@gmail.com',
                'A mail from you from Python',
                '<b>A mail from you from Python</b><br><br>' +
                'So happy to hear from you!')
    input("Success!")

print(__name__)
input("Wait!!")
if __name__ == '__main__':
    main()
导入base64
导入imaplib
导入json
导入smtplib
导入urllib.parse
导入urllib.request
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
导入lxml.html
谷歌账户库https://accounts.google.com'
重定向_URI='urn:ietf:wg:oauth:2.0:oob'
谷歌客户端ID=“”
谷歌客户端密码=“”
谷歌刷新令牌=无
def命令到url(命令):
返回“%s/%s%”(GOOGLE\u ACCOUNTS\u BASE\u URL,命令)
def url_转义(文本):
返回urllib.parse.quote(text,safe='~-.\uquote)
def url_unescape(文本):
返回urllib.parse.unquote(文本)
def url_格式_参数(参数):
param_fragments=[]
对于排序中的参数(params.items(),key=lambda x:x[0]):
param_fragments.append(“%s=%s%”(参数[0],url_转义(参数[1]))
返回“&”.join(参数片段)
def生成权限url(客户端id,范围=)https://mail.google.com/'):
参数={}
参数['client_id']=client_id
params['redirect_uri']=redirect_uri
参数['scope']=scope
参数['response_type']='code'
返回'%s?%s'(命令\u到\u url('o/oauth2/auth'),url\u格式\u参数(params))
def呼叫授权令牌(客户端id、客户端密码、授权码):
参数={}
参数['client_id']=client_id
参数['client_secret']=client_secret
参数['code']=授权码
params['redirect_uri']=redirect_uri
参数['grant_type']='AUTHORITION_code'
请求\u url=命令\u到\u url('o/oauth2/token')
response=urllib.request.urlopen(request_url,urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8'))
返回json.loads(响应)
def call_refresh_令牌(客户端id、客户端机密、刷新令牌):
参数={}
参数['client_id']=client_id
参数['client_secret']=client_secret
参数['refresh_token']=refresh_token
参数['grant_type']='refresh_token'
请求\u url=命令\u到\u url('o/oauth2/token')
response=urllib.request.urlopen(request_url,urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8'))
返回json.loads(响应)
def generate_oauth2_字符串(用户名、访问令牌,as_base64=False):
身份验证字符串='user=%s\1auth=承载者%s\1\1'(用户名,访问令牌)
如果为64:
auth_string=base64.b64编码(auth_string.encode('ascii')).decode('ascii'))
返回auth_字符串
def测试imap(用户、验证字符串):
imap_conn=imaplib.IMAP4_SSL('imap.gmail.com'))
imap_conn.debug=4
imap连接验证('XOAUTH2',lambda x:auth\u字符串)
imap_连接选择(“收件箱”)
def test_smpt(用户,base64_验证字符串):
smtp_conn=smtplib.smtp('smtp.gmail.com',587)
smtp连接设置调试级别(True)
smtp_连接ehlo(“测试”)
smtp_conn.starttls()
smtp_conn.docmd('AUTH','XOAUTH2'+base64_AUTH_字符串)
def get_授权(谷歌客户端id、谷歌客户端机密):
范围=”https://mail.google.com/"
打印('导航到以下URL进行身份验证:',生成权限\ URL(谷歌\客户端\ id,范围))
授权\ U代码=输入('输入验证代码:')
响应=调用\授权\令牌(谷歌\客户端\ id、谷歌\客户端\机密、授权\代码)
返回响应['refresh_token'],响应['access_token'],响应['expires_in']
def刷新授权(谷歌客户端id、谷歌客户端密码、刷新令牌):
响应=调用\u刷新\u令牌(google\u客户端\u id、google\u客户端\u机密、刷新\u令牌)
返回响应['access_token'],响应['expires_in']
def发送邮件(从地址、到地址、主题、消息):
访问\u令牌,过期\u in=刷新\u授权(谷歌\u客户端\u ID、谷歌\u客户端\u密码、谷歌\u刷新\u令牌)
auth_string=generate_oauth2_string(fromaddr,access_令牌,as_base64=True)
msg=MIMEMultipart('相关')
msg['Subject']=主语
msg['From']=fromaddr
msg['To']=toaddr
msg.preamble='这是MIME格式的多部分消息。'
msg_alternative=MIMEMultipart(‘alternative’)
msg.attach(msg_可选)
part_text=MIMEText(lxml.html.fromstring(message).text_content().encode('utf-8'),'plain',_charset='utf-8')
part_html=MIMEText(message.encode('utf-8'),'html',_charset='utf-8')
msg_可选。附加(部分文字)
msg_alternative.attach(part_html)
server=smtplib.SMTP('SMTP.gmail.com:587')
ehlo(GOOGLE\u客户端\u ID)
server.starttls()
docmd('AUTH','XOAUTH2'+AUTH\u字符串)
sendmail(fromaddr,toaddr,msg.as\u string())
server.quit()
def main():
如果GOOGLE_REFRESH_TOKEN为无:
打印('未找到刷新令牌,正在获取一个')
刷新\u令牌、访问\u令牌、过期\u in=获取\u授权(GOOGLE\u客户端\u ID、GOOGLE\u客户端\u机密)
打印('将以下内容设置为您的谷歌刷新令牌:',刷新令牌)
退出()
发送电子邮件('----------@gmail.com','----------@gmail.com',
“来自Python的您的邮件”,
'来自Python的您的邮件'+
“很高兴收到你的来信!”)
输入(“成功!”)
打印(名称)
输入(“等待!!”)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
当我在pyCharm中运行代码时效果很好,当我使用pyinstaller时,它会创建exe。当我运行EXE时,它将打开一个没有文本的新cmd prmpt,然后关闭。你知道为什么它不在屏幕上打印名字或“等等!!”吗? 我将文件命名为main,它在PyCharm中工作得非常好。
我不熟悉在IDE中工作的代码的疑难解答,它不作为exe执行。是否有基本的故障排除指南?

大多数问题都是由导入的模块引起的错误

我有两种想法

  • 使用异常处理并在发生错误时使用
    traceback.format_exc()
    显示内容
  • 错误通常与
    sys.stderr
    相关,所以
    import sys
    from pathlib import Path
    from os import startfile
    import traceback
    
    
    DEBUG = True
    
    
    class CaptureStderr:
        __slots__ = ('debug_flag',
                     'original',
                     'log',)
    
        def __init__(self, debug_flag=False, log=None):
            self.debug_flag = debug_flag
            self.original = sys.stderr  # Keep track of original
            self.log = log
    
        def new_log_file(self, log_path: Path = Path('temp.log').resolve()):
            self.log = open(str(log_path), 'w')
            return self.log
    
        def start(self):
            """ Start filtering and redirecting stderr """
            sys.stderr = self
    
        def stop(self):
            """ Stop filtering and redirecting stderr """
            sys.stderr = self.original
    
        def write(self, message: str):
            """ When sys.stderr.write is called, it will re directed here"""
            if not self.debug_flag:
                self.original.write(message)
                self.original.flush()
                return
            if self.log:
                self.log.write(message)
    
    
    def main():
        ...
    
    
    if __name__ == '__main__':
        try:  # method 1
            from .notexistmodule import notexistclass
            # Put modules that you are not sure whether it is 100% import successful on here.
            main()
        except:
            print(traceback.format_exc())
    
        # method 2: redirect sys.stderr
        cs = CaptureStderr(DEBUG)
        cs.new_log_file(Path('error.log'))
        cs.start()
        from .notexistmodule2 import notexistclass2
        main()
        cs.stop()
        startfile(cs.log.name)
    
    
    start C:\Path\To\.exe
    pause