py2exe com dll问题

2023-12-30

我正在尝试用 python 制作一个 com dll。但我尝试注册到编译的 dll 时出现错误消息“运行时错误 r6034”和“无法加载 python dll”这个问题的解决方案是什么?

mycode :

设置.py:

# This is the distutils script for creating a Python-based com dll
# server using ctypes.com.  This script should be run like this:
#
#  % python setup.py py2exe
#
# After you run this (from this directory) you will find two directories here:
# "build" and "dist".  The .dll file in dist is what you are looking for.
##############################################################################

from distutils.core import setup
import py2exe
import sys

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # for the version info resources (Properties -- Version)
        self.version = "0.0.1"
        self.company_name = "my company"
        self.copyright = "2006, my company"
        self.name = "my com server name"

my_com_server_target = Target(
    description = "my com server",
    # use module name for ctypes.com dll server
    modules = ["view.view"],
    # the following line embeds the typelib within the dll
    #other_resources = [("TYPELIB", 1, open(r"view\view.tlb", "rb").read())],
    # we only want the inproc (dll) server
    create_exe = False
    )

setup(
    name="my_com_server",
    # the following two parameters embed support files within dll file
    options={"py2exe": {"bundle_files": 1, }},
    zipfile=None,
    version="0.0.1",
    description="my com server",
    # author, maintainer, contact go here:
    author="First Last",
    author_email="some_name@some_company.com",
    packages=["view"],
    ctypes_com_server=[my_com_server_target]
    )

和view.py:

# -*- coding: utf-8 -*-

# A sample context menu handler.
# Adds a 'Hello from Python' menu entry to .py files.  When clicked, a
# simple message box is displayed.
#
# To demostrate:
# * Execute this script to register the context menu.
# * Open Windows Explorer, and browse to a directory with a .py file.
# * Right-Click on a .py file - locate and click on 'Hello from Python' on
#   the context menu.

import ConfigParser
import os.path
import urllib
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con

IContextMenu_Methods = ["QueryContextMenu", "InvokeCommand", "GetCommandString"]
IShellExtInit_Methods = ["Initialize"]

#HKCR Key   Affected object types
#*  All files
#AllFileSystemObjects   All regular files and file folders
#Folder     All folders, virtual and filesystem
#Directory  File folders
#Drive  Root folders of all system drives
#Network    Entire network
#NetShare   All network shares

TYPES = [
    '*',
    'Directory',
    ]
SUBKEY = 'MindRetrieve'

def alertError(hwnd, exc):
    win32gui.MessageBox(hwnd, str(exc), str(exc.__class__), win32con.MB_OK)


class ShellExtension:
    _reg_progid_ = "MindRetrieve.ShellExtension.ContextMenu"
    _reg_desc_ = "MindRetrieve Shell Extension (context menu)"
    _reg_clsid_ = "{ABB05546-EB55-4433-B068-A57667706828}"

    _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
    _public_methods_ = IContextMenu_Methods + IShellExtInit_Methods

    def Initialize(self, folder, dataobj, hkey):
        print "Init", folder, dataobj, hkey
        self.dataobj = dataobj

    def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
        print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags

        try:
            # Query the items clicked on
#            files = self.getFiles()
#            msg =  len(files) > 1 and '&Tag %s files' % len(files) or '&Tag with MindRetrieve'
#            # TODO: we do not support tagging multiple files now
#            if not(files):
#                return
            msg = '&Tag with MindRetrieve'

            idCmd = idCmdFirst
            items = []
            if (uFlags & 0x000F) == shellcon.CMF_NORMAL: # Check == here, since CMF_NORMAL=0
                print "CMF_NORMAL..."
                items.append(msg)
            elif uFlags & shellcon.CMF_VERBSONLY:
                print "CMF_VERBSONLY..."
                items.append(msg)# + " - shortcut")
            elif uFlags & shellcon.CMF_EXPLORE:
                print "CMF_EXPLORE..."
                items.append(msg)# + " - normal file, right-click in Explorer")
            elif uFlags & shellcon.CMF_DEFAULTONLY:
                print "CMF_DEFAULTONLY...\r\n"
            else:
                print "** unknown flags", uFlags
            win32gui.InsertMenu(hMenu, indexMenu,
                                win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
                                0, None)
            indexMenu += 1
            for item in items:
                win32gui.InsertMenu(hMenu, indexMenu,
                                    win32con.MF_STRING|win32con.MF_BYPOSITION,
                                    idCmd, item)
                indexMenu += 1
                idCmd += 1

            win32gui.InsertMenu(hMenu, indexMenu,
                                win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
                                0, None)
            indexMenu += 1
            return idCmd-idCmdFirst # Must return number of menu items we added.

        except Exception, e:
            alertError(hwnd, e)
            raise


    def InvokeCommand(self, ci):
        mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci

        try:
            files = self.getFiles()
            if not files:
                return
            fname = files[0]

#            win32gui.MessageBox(hwnd, fname,  str(fname.__class__), win32con.MB_OK)

            fname = fname.encode('utf-8')
            file_url = urllib.pathname2url(fname)

    # 2005-12-20 Test urllib.pathname2url()
    #
    #>>> urllib.pathname2url(r'c:\tung\wäi')
    #'///C|/tung/w%84i'
    #>>> urllib.pathname2url(r'\tung\wäi')
    #'/tung/w%84i'
    #>>> urllib.pathname2url(r'tung\wäi')
    #'tung/w%84i'

            # prefer ':' as the drive separator rather than '|'
            if file_url.startswith('///') and file_url[4:5] == '|':
                file_url = file_url.replace('|',':',1)

            if file_url.startswith('//'):
                file_url = 'file:' + file_url
            elif file_url.startswith('/'):
                file_url = 'file://' + file_url
            else:
                # fname is a relative filename? Should not happen!
                file_url = 'file:///' + file_url

            url = getBaseURL() + '?url=' + urllib.quote(file_url)
            shell.ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                                 lpFile=url,
                                 nShow=win32con.SW_NORMAL,
                                )
        except Exception, e:
            alertError(hwnd, e)
            raise


    def GetCommandString(self, cmd, typ):
        return "&Tag with MindRetrieve"


    def getFiles(self):
        format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
        sm = self.dataobj.GetData(format_etc)
        num_files = shell.DragQueryFile(sm.data_handle, -1)
        files = [shell.DragQueryFile(sm.data_handle, i) for i in range(num_files)]
        return files


def getConfigPath():
    """ get the DLL path from registry """
    import _winreg

    # _winreg.QueryValue() may throw WindowsError

    # COM server registration in deployed environment
    # e.g. HKEY_CLASSES_ROOT\CLSID\{ABB05546-EB55-4433-B068-A57667706828}\InprocServer32
    #       =c:\Program Files\MindRetrieve\context_menu.dll
    subkey = 'CLSID\\%s\\InprocServer32' % ShellExtension._reg_clsid_
    path = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
    head, tail = os.path.split(path)
    # quick check if this is in deployed environment
    if os.path.isabs(head):
        return head

    # Otherwise assume in development environment
    # e.g. HKEY_CLASSES_ROOT\CLSID\{ABB05546-EB55-4433-B068-A57667706828}\PythonCOMPath
    #       =g:\bin\py_repos\mindretrieve\trunk\minds\weblib\win32
    subkey = 'CLSID\\%s\\PythonCOMPath' % ShellExtension._reg_clsid_
    path = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
    idx = path.lower().rfind('minds')   # truncate trailing 'minds\weblib\win32'
    if idx > 0:
        path = path[:idx-1]
    return path



def getHTTPAdminPort():
    """ get HTTP.admin_port from config.ini """
    pathname = os.path.join(getConfigPath(), 'config.ini')
    cp = ConfigParser.ConfigParser()
    cp.read(pathname)
    admin_port = cp.getint('http','admin_port')
    return admin_port


def getBaseURL():
    """ get the base URL """
    port = getHTTPAdminPort()
    return 'http://localhost:%s/weblib/_' % port


def DllRegisterServer():
    import _winreg
    for typ in TYPES:
        # e.g. HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\MindRetrieve
        key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex" % typ)
        subkey = _winreg.CreateKey(key, "ContextMenuHandlers")
        subkey2 = _winreg.CreateKey(subkey, SUBKEY)
        _winreg.SetValueEx(subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
    print ShellExtension._reg_desc_, "registration complete."


def DllUnregisterServer():
    import _winreg
    for typ in TYPES:
        try:
            # e.g. HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\MindRetrieve
            key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, "%s\\shellex\\ContextMenuHandlers\\%s" % (typ, SUBKEY))
        except WindowsError, details:
            import errno
            if details.errno != errno.ENOENT:
                raise
    print ShellExtension._reg_desc_, "unregistration complete."


def main(argv):
    # assume argv == sys.argv
    from win32com.server import register
    register.UseCommandLine(ShellExtension,
                   finalize_register = DllRegisterServer,
                   finalize_unregister = DllUnregisterServer)


def test(argv):
    """ adhoc tests """
    print 'URL:', getBaseURL()


if __name__=='__main__':
    import sys
    if '-t' not in sys.argv:
        main(sys.argv)
    else:
        test(sys.argv)

Per the docs http://msdn.microsoft.com/en-us/library/ms235560(VS.80).aspx关于错误 R6034,这意味着您加载 C 运行时库是错误的,因为您缺少“清单”。每这个线程 http://forums.devshed.com/python-programming-11/py2exe-manifests-and-vc-redist-dlls-600827.html,看来所需的方法只是:

我发现如果我制作一个清单文件 并复制内容 python.exe.manifest 一切都是 工作正常

(无法验证这是否属实,因为我仍然没有可用的 Windows——我现在拥有一台便宜的翻新 Windows 机器,得到它只是为了尝试帮助更多人解决此类问题,但找不到防病毒磁盘,并且没有当然,我无法安全地上网)。

py2exe 的教程 http://www.py2exe.org/index.cgi/Tutorial#Step521涵盖了捆绑运行时库并为此制定清单的问题,并且比上面引用的简短解释更详细。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

py2exe com dll问题 的相关文章

  • 为什么 matplotlib 底图没有绘制地图中某些区域的颜色?

    下面的代码应该为越南的所有州着色 import pandas as pd import matplotlib pyplot as plt from mpl toolkits basemap import Basemap fig ax plt
  • 根据另一个数据框中找到的范围填充数据框中的列

    我试图根据该记录的索引值是否落在另一个数据框中的两列定义的范围内来填充数据框中的列 df1 看起来像 a 0 4 1 45 2 7 3 5 4 48 5 44 6 22 7 89 8 45 9 44 10 23 df2 是 START ST
  • 如何将 Google Cloud Storage 中的许多文件设为私有?

    我进行了很多研究 但无法为此提出解决方案 以下是我用来在 GCP 中公开所有文件的代码 def make blob public bucket name blob name Makes a blob publicly accessible
  • 测试交互式Python程序

    我想知道python的哪些测试工具支持交互式程序的测试 例如 我有一个由以下人员启动的应用程序 python dummy program py gt gt Hi whats your name Joseph 我想要仪器Joseph所以我可以
  • Pygame 让精灵按照给定的旋转行走

    很久以前我做了一个Scratch脚本 我想用Pygame将其转换为Python 有很多示例显示图像的旋转 但我想知道如何更改精灵的旋转以使其沿给定方向移动 而不更改图像 这是我的暂存代码 这是我的 Pygame 精灵类 class Star
  • 如何使用 Twython 将 oauth_callback 值传递给 oauth/request_token

    Twitter 最近刚刚强制执行以下规定 1 您必须通过oauth callbackoauth request token 的值 这不是可选的 即使您已经在 dev twitter com 上设置了一个 如果您正在执行带外 OAuth 请通
  • 类型错误:translate() 只接受一个参数(给定 2 个参数)[重复]

    这个问题在这里已经有答案了 我的代码在 python 2 x 版本上运行良好 但是当我尝试在 python 3 x 版本上运行它时 出现错误 主题 需要缩写短信编码中的任何消息 Code def sms encoding data star
  • Scrapy Splash,如何处理onclick?

    我正在尝试抓取以下内容 我能够收到响应 但我不知道如何访问以下项目的内部数据以抓取它 我注意到访问这些项目实际上是由 JavaScript 和分页处理的 这种情况我该怎么办 下面是我的代码 import scrapy from scrapy
  • 在Python中清理属于不同语言的文本

    我有一个文本集合 其中的句子要么完全是英语 印地语或马拉地语 每个句子附加的 id 为 0 1 2 分别代表文本的语言 无论任何语言的文本都可能有 HTML 标签 标点符号等 我可以使用下面的代码清理英语句子 import HTMLPars
  • Python ElementTree 获取带有命名空间的属性

    我试图访问 XML 中的 def 所以在这个例子中我会得到Evolus Common PlainTextV2作为输出 我似乎无法弄清楚如何获取具有名称空间的属性 如果我想得到id它工作得很好 Python for content ns in
  • 如何不断地将 STDOUT 发送到我的 python TCP 服务器?

    我有简单的 python echo 服务器 它使用套接字 并向客户端回显随机数 我有另一个程序 每 2 秒将值打印到标准输出 如果它只是一个脚本 我可以像这样重定向 stdout python script py 并像这样在脚本中获取它da
  • 如何使用 Python 实现并行 gzip 压缩?

    使用python压缩大文件 https stackoverflow com questions 9518705 big file compression with python给出了一个很好的例子来说明如何使用例如bz2 纯粹用 Pytho
  • 向结构化 numpy 数组添加字段

    将字段添加到结构化 numpy 数组的最简洁方法是什么 是否可以破坏性地完成 或者是否有必要创建一个新数组并复制现有字段 每个字段的内容是否连续存储在内存中 以便可以有效地完成此类复制 如果您使用 numpy 1 3 还有 numpy li
  • 从 python 文件调用 Julia 函数

    我能够创建一个 docker 环境 然后按照这个线程我有一个用 Julia 编写的高性能函数 如何从 Python 中使用它 https stackoverflow com questions 64241264 i have a high
  • 如何输入可变的默认参数

    Python 中处理可变默认参数的方法是将它们设置为无 https stackoverflow com a 366430 5049813 例如 def foo bar None bar if bar is None else bar ret
  • 给定一个字符串,如何删除所有重复的连续字母?

    如何从字符串中删除两个连续的字母 例如 a str hii thherre 应该成为 hi there 我尝试这样做 a str join sorted set a str key a str index 但是 我得到 hi ter 是的
  • scikit-learn kmeans 聚类的初始质心

    如果我已经有一个可以作为初始质心的 numpy 数组 我该如何正确初始化 kmeans 算法 我正在使用 scikit learn Kmeans 类 这个帖子 具有选定初始中心的 k 均值 https stackoverflow com q
  • 跟踪白色背景中的白球(Python/OpenCV)

    我在 Python 3 中使用 OpenCV 来检测白场上的白 黑球 并给出它的精确 x y 半径 和颜色 我使用函数 cv2 Canny 和 cv2 findContours 来找到它 但问题是 cv2 Canny 并不总是检测到圆的完整
  • 具有重复值的 Sqlite 列

    就说专栏吧aSQLite 数据库的非常重复 始终有相同的 4 个值 其他值可能稍后出现 但不同值的数量将少于 1000 个 VALUES hello world it s a shame to store this str many tim
  • 如何从Python枚举类中获取所有值?

    我正在使用 Enum4 库创建一个枚举类 如下所示 class Color Enum RED 1 BLUE 2 我要打印 1 2 作为某处的列表 我怎样才能实现这个目标 您可以执行以下操作 e value for e in Color

随机推荐