Unicode在.py脚本中工作,但不在冻结.exe [Python 2.7]

时间:2017-02-03 00:55:43

标签: python python-2.7 unicode encoding freeze

所以,我正在编写这个代码,将数据发送到服务器,以显示给用户。我遇到了unicode角色的问题。当我从IDE运行脚本时,服务器获取“正确”的unicode str,并且显示正确,但是在使用py2exe或cx_Freeze冻结脚本并运行.exe文件时,显示器由??组成。 ? ??? ???而不是字符。

我假设这是由于用于冻结脚本的编码?我对编码的经验很少,所以请原谅我的无知。以下是有问题的代码:

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  #someone suggested this would solve the problem

import os, time, json, urllib2, getpass, socket, subprocess, ast, ctypes, sys

reload(sys)  
sys.setdefaultencoding('UTF8') # another suggestion was to force UTF-8 to be def encoding
subprocess.Popen('chcp 65001', shell=True) # thought I'd give it a go forcing cmd to use utf-8

EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW

def get_active_window(): #function that gives me the title of the active window (unicode)
    hwnd = ctypes.windll.user32.GetForegroundWindow()
    length = GetWindowTextLength(hwnd)
    buff = ctypes.create_unicode_buffer(length + 1)
    GetWindowText(hwnd, buff, length + 1)
    return buff.value

def send_server(data, url): #sending data to the server
    req = urllib2.Request(url)
    req.add_header('Content-Type', 'application/json')
    return urllib2.urlopen(req, data).read()

send_server(get_active_window(), "http://foo.com");

提醒一下,这在从IDE运行时有效,所以当我冻结脚本时,我猜测会出现问题吗?

先谢谢你的帮助!!!!

编辑:我已修复编码以匹配编码:名称,仍然没有运气

1 个答案:

答案 0 :(得分:1)

我在这里有一个非常相似的脚本做同样的事情我已经使用CxFreeze来分发我的应用程序,但它与你的应用程序略有不同。我也使用过Python2.7并在Windows XP,7,8和10上进行了测试。

但在尝试使用我的解决方案之前,我已经意识到您的编码行是错误的,因为它需要像according to docs这样:

  

编码:名称或编码=评论中的名称。

所以,你必须 put:或=

如果您愿意,可以尝试这种方式对我有用:

from win32gui import GetWindowText, GetForegroundWindow 
active_window = GetWindowText(GetForegroundWindow())

我已使用this great website下载win32gui

相关问题