使用py2exe打包时不包含密钥环模块

时间:2013-11-08 05:31:27

标签: python json py2exe python-keyring mercurial-keyring

我正在使用Windows上的 python 2.7和keyring-3.2.1 制作应用。在我在eclipse上的python代码中,我使用了

import keyring
keyring.set_password("service","jsonkey",json_res)
json_res= keyring.get_password("service","jsonkey")

工作正常,因为我在密钥环中存储json响应。但是,当我使用py2exe将python代码转换为exe时,它会在制作dist时显示导入错误密钥环。请建议如何在py2exe中包含密钥环。

Traceback (most recent call last):
  File "APP.py", line 8, in <module>
  File "keyring\__init__.pyc", line 12, in <module>
  File "keyring\core.pyc", line 15, in <module>
  File "keyring\util\platform_.pyc", line 4, in <module>
  File "keyring\util\platform.pyc", line 29, in <module>
AttributeError: 'module' object has no attribute 'system'

platform_.py代码为:

from __future__ import absolute_import

import os
import platform

def _data_root_Windows():
    try:
        root = os.environ['LOCALAPPDATA']
    except KeyError:
        # Windows XP
        root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
    return os.path.join(root, 'Python Keyring')

def _data_root_Linux():
    """
    Use freedesktop.org Base Dir Specfication to determine storage
    location.
    """
    fallback = os.path.expanduser('~/.local/share')
    root = os.environ.get('XDG_DATA_HOME', None) or fallback
    return os.path.join(root, 'python_keyring')

# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)

platform.py代码为:

import os
import sys

# While we support Python 2.4, use a convoluted technique to import
#  platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
#  and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']

def _data_root_Windows():
    try:
        root = os.environ['LOCALAPPDATA']
    except KeyError:
        # Windows XP
        root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
    return os.path.join(root, 'Python Keyring')

def _data_root_Linux():
    """
    Use freedesktop.org Base Dir Specfication to determine storage
    location.
    """
    fallback = os.path.expanduser('~/.local/share')
    root = os.environ.get('XDG_DATA_HOME', None) or fallback
    return os.path.join(root, 'python_keyring')

# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)

1 个答案:

答案 0 :(得分:7)

您报告的问题是由于包含无效模块的环境造成的,可能是因为一个版本的密钥环安装不正确。您需要确保已删除旧版密钥环的残余内容。特别是,请确保您的站点包中没有名为keyring \ util \ platform。*的文件。

然而,在这样做之后,你会遇到另一个问题。密钥环loads its backend modules programmatically,因此py2exe不会检测到它们。

要解决此问题,您需要在py2exe选项中添加“包”声明,以明确包含keyring.backends包。我用Python 2.7调用了以下setup.py脚本,将'app.py'(导入密钥环)转换为exe:

from distutils.core import setup
import py2exe

setup(
    console=['app.py'],
    options=dict(py2exe=dict(
        packages='keyring.backends',
    )),
)

生成的app.exe将导入并调用密钥环。