Exemplo n.º 1
0
    True, False
except NameError:
    # Maintain compatibility with Python 2.2
    True, False = 1, 0

try:
    filesystem_encoding = sys.getfilesystemencoding()
except AttributeError:
    filesystem_encoding = "mbcs"

# Work out our "application directory", which is
# the directory of our main .py/.dll/.exe file we
# are running from.
if hasattr(sys, "frozen"):
    assert sys.frozen == "dll", "outlook only supports inproc servers"
    this_filename = win32api.GetModuleFileName(sys.frozendllhandle)
else:
    try:
        this_filename = os.path.abspath(__file__)
    except NameError:  # no __file__ - means Py2.2 and __name__=='__main__'
        this_filename = os.path.abspath(sys.argv[0])
# See if we can use the new bsddb module. (The old one is unreliable
# on Windows, so we don't use that)
try:
    import bsddb3 as bsddb
    # bsddb3 is definitely not broken
    use_db = True
except ImportError:
    # Not using the 3rd party bsddb3, so try the one in the std library
    try:
        import bsddb
Exemplo n.º 2
0
    def __init__(self):
        wx.Frame.__init__(self, None, -1, APP_TITLE, style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
        # 默认style是下列项的组合:wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN 
        
        self.SetBackgroundColour(wx.Colour(224,224,224))
        self.SetSize((800, 600))
        self.Center()

        if hasattr(sys, "frozen") and getattr(sys, "frozen"):
            exeName = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
            icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        else:
            icon = wx.Icon(APP_ICON, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        
        # left
        panelLeft = wx.BoxSizer(wx.VERTICAL)
        
        gridDatas = []

        self.gridTable = wx.grid.Grid(self, -1, pos=(5,5), size=(400, 400), style=wx.WANTS_CHARS)
        
        self.infoTable = FileListGridTable(gridDatas)
        self.gridTable.SetTable(self.infoTable, True)

        self.gauge = wx.Gauge(self, range = 20, size = (250, 25), style = wx.GA_HORIZONTAL)
        panelLeft.Add(self.gridTable, 0, wx.EXPAND|wx.ALL, 5)
        panelLeft.Add(self.gauge, 0, wx.EXPAND|wx.ALL, 5)

        # right
        panelRight = wx.BoxSizer(wx.VERTICAL)

        btnOpenFiles = wx.Button(self, -1, u'Open', size=(50, 50))
        btnOpenFiles.Bind(wx.EVT_BUTTON, self.OpenFiles)
        btnMoveUp = wx.Button(self, -1, u'↑', size=(50, 50))
        btnMoveUp.Bind(wx.EVT_BUTTON, self.MoveUp)
        btnMoveDown = wx.Button(self, -1, u'↓', size=(50, 50))
        btnMoveDown.Bind(wx.EVT_BUTTON, self.MoveDown)
        btnMerge = wx.Button(self, -1, u'Merge', size=(50,50))
        btnMerge.Bind(wx.EVT_BUTTON, self.MergePDFFiles)
        btnClear = wx.Button(self, -1, u'Clear', size=(50,50))
        btnClear.Bind(wx.EVT_BUTTON, self.ClearFiles)
        panelRight.Add(btnOpenFiles, 0, wx.ALL, 10)  
        panelRight.Add(btnMoveUp, 0, wx.ALL, 10)  
        panelRight.Add(btnMoveDown, 0, wx.ALL, 10)  
        panelRight.Add(btnMerge, 0, wx.ALL, 10)
        panelRight.Add(btnClear, 0, wx.ALL, 10)


        mainBox = wx.BoxSizer(wx.HORIZONTAL)
        mainBox.Add(panelLeft, 1, wx.EXPAND|wx.LEFT|wx.TOP|wx.BOTTOM, 5)     
        mainBox.Add(panelRight, 0, wx.EXPAND|wx.ALL, 20)          
        
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_SIZE, self.OnResize)     
        
        self.SetAutoLayout(True)
        self.SetSizer(mainBox)
        self.Layout()
          
        logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.logger = logging.getLogger(__name__)
Exemplo n.º 3
0
    def __init__(self, Parent):
        '''构造函数'''
        wx.Frame.__init__(self, Parent, -1, APP_TITLE)
        self.SetBackgroundColour(wx.Colour(224, 224, 224))
        self.SetSize((800, 600))
        self.Center()

        if hasattr(sys, "frozen") and getattr(sys, "frozemn") == "windows_exe":
            exeName = win32api.GetModuleFileName(
                win32api.GetModuleHandle(None))
            icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        else:
            icon = wx.Icon(APP_ICON, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        self.tb1 = self._CreateToolBar()
        self.tb2 = self._CreateToolBar()
        #self.tbv = self._CreateToolBar('V')

        p_left = wx.Panel(self, -1)

        p_center0 = wx.Panel(self, -1)

        p_center1 = wx.Panel(self, -1)
        p_bottom = wx.Panel(self, -1)

        btn = wx.Button(p_left, -1, u'切换', pos=(30, 200), size=(100, -1))
        btn.Bind(wx.EVT_BUTTON, self.OnSwitch)

        texto = wx.StaticText(p_center0,
                              -1,
                              u'xia',
                              pos=(0, 0),
                              size=(200, -1),
                              style=wx.ALIGN_LEFT)
        text1 = wx.StaticText(p_center1,
                              -1,
                              u'我是第2页',
                              pos=(0, 0),
                              size=(200, -1),
                              style=wx.ALIGN_LEFT)

        self._CreateprogressBar(p_center0)

        self._mgr = aui.AuiManager()
        self._mgr.SetManagedWindow(self)

        self._mgr.AddPane(
            self.tb1,
            aui.AuiPaneInfo().Name("ToolBar1").Caption(u"工具条").ToolbarPane().
            Top().Row(0).Position(0).Floatable(False))

        self._mgr.AddPane(
            self.tb2,
            aui.AuiPaneInfo().Name("ToolBar2").Caption(
                u"工具条").ToolbarPane().Top().Row(0).Position(1).Floatable(True))
        '''
        self._mgr.AddPane(self.tbv,
                          aui.AuiPaneInfo().Name("ToolBarV").Caption(
                              u"工具条").ToolbarPane().Right().Floatable(True)
                          )
        '''
        self._mgr.AddPane(
            p_left,
            aui.AuiPaneInfo().Name("LeftPanel").Left().Layer(1).MinSize(
                (200, -1)).Caption(u"操作区").MinimizeButton(True).MaximizeButton(
                    True).CloseButton(True))

        self._mgr.AddPane(
            p_center0,
            aui.AuiPaneInfo().Name("CenterPanel0").CenterPane().Show())

        self._mgr.AddPane(
            p_center1,
            aui.AuiPaneInfo().Name("CenterPanel1").CenterPane().Hide())

        self._mgr.AddPane(
            p_bottom,
            aui.AuiPaneInfo().Name("BottomPanel").Bottom().MinSize(
                (-1,
                 100)).Caption(u"消息区").CaptionVisible(False).Resizable(True))

        self._mgr.Update()
Exemplo n.º 4
0
        self.__analizar_errores(ret)
        array = ret.get("arrayPuntosEmision", [])
        if sep is None:
            return dict([(it["codigo"], it["descripcion"]) for it in array])
        else:
            return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
                    (it["codigo"], it["descripcion"]) for it in array]


# busco el directorio de instalación (global para que no cambie si usan otra dll)
if not hasattr(sys, "frozen"):
    basepath = __file__
elif sys.frozen == "dll":
    import win32api

    basepath = win32api.GetModuleFileName(sys.frozendllhandle)
else:
    basepath = sys.executable
INSTALL_DIR = WSRemHarina.InstallDir = get_install_dir()


def main():
    global DEBUG, XML, CONFIG_FILE, H**O
    if "--ayuda" in sys.argv:
        print(LICENCIA)
        print(AYUDA)
        sys.exit(0)

    if "--register" in sys.argv or "--unregister" in sys.argv:
        import win32com.server.register
Exemplo n.º 5
0
import pythoncom
if not hasattr(sys, "frozen"):
    # standard exes have none.
    sys.frozen = pythoncom.frozen = 1
else:
    # com DLLs already have sys.frozen set to 'dll'
    pythoncom.frozen = sys.frozen

# Add some extra imports here, just to avoid putting them as "hidden imports"
# anywhere else - this script has the best idea about what it needs.
# (and hidden imports are currently disabled :)
import win32com.server.policy, win32com.server.util

# Patchup sys.argv for our DLL
if sys.frozen == "dll" and not hasattr(sys, "argv"):
    sys.argv = [win32api.GetModuleFileName(sys.frozendllhandle)]
# We assume that py2exe has magically set com_module_names
# to the module names that expose the COM objects we host.
# Note that here all the COM modules for the app are imported - hence any
# environment changes (such as sys.stderr redirection) will happen now.
com_modules = []
try:
    for name in com_module_names:
        __import__(name)
        com_modules.append(sys.modules[name])
except NameError:
    print "This script is designed to be run from inside py2exe"
    sys.exit(1)
del name

Exemplo n.º 6
0
Arquivo: util.py Projeto: hnur/pywin32
def RegisterPythonServer(filename, progids=None, verbose=0):
    if progids:
        if isinstance(progids, basestring):
            progids = [progids]
        # we know the CLSIDs we need, but we might not be an admin user
        # and otherwise unable to register them.  So as long as the progids
        # exist and the DLL points at our version, assume it already is.
        why_not = None
        for progid in progids:
            try:
                clsid = pythoncom.MakeIID(progid)
            except pythoncom.com_error:
                # no progid - not registered.
                break
            # have a CLSID - open it.
            try:
                HKCR = _winreg.HKEY_CLASSES_ROOT
                hk = _winreg.OpenKey(HKCR, "CLSID\\%s" % clsid)
                dll = _winreg.QueryValue(hk, "InprocServer32")
            except WindowsError:
                # no CLSID or InProcServer32 - not good!
                break
            ok_files = [
                os.path.basename(pythoncom.__file__),
                'pythoncomloader%d%d.dll' %
                (sys.version_info[0], sys.version_info[1])
            ]
            if os.path.basename(dll) not in ok_files:
                why_not = "%r is registered against a different Python version (%s)" % (
                    progid, dll)
                break
        else:
            #print "Skipping registration of '%s' - already registered" % filename
            return
    # needs registration - see if its likely!
    try:
        from win32com.shell.shell import IsUserAnAdmin
    except ImportError:
        print "Can't import win32com.shell - no idea if you are an admin or not?"
        is_admin = False
    else:
        try:
            is_admin = IsUserAnAdmin()
        except pythoncom.com_error:
            # old, less-secure OS - assume *is* admin.
            is_admin = True
    if not is_admin:
        msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[
            0]
        if why_not:
            msg += "\n(registration check failed as %s)" % why_not
        # throw a normal "class not registered" exception - we don't report
        # them the same way as "real" errors.
        raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1)
    # so theoretically we are able to register it.
    cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0),
                                               filename)
    if verbose:
        print "Registering engine", filename


#       print cmd
    rc = os.system(cmd)
    if rc:
        print "Registration command was:"
        print cmd
        raise RuntimeError("Registration of engine '%s' failed" % filename)
Exemplo n.º 7
0
    def __init__(self):

        wx.Frame.__init__(self,None,-1,APP_TITLE,style=wx.DEFAULT_FRAME_STYLE^wx.RESIZE_BORDER)
        self.SetBackgroundColour(wx.Colour(244,244,244))
        self.SetSize((800,1000))
        self.Center()

        if hasattr(sys, "frozen") and getattr(sys, "frozen") == "windows_exe":
            exe_name = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
            icon = wx.Icon(exe_name,wx.BITMAP_TYPE_ICO)
        else:
            icon = wx.Icon(APP_ICON,wx.BITMAP_TYPE_ICO)

        self.SetIcon(icon)

        sizer_main = wx.GridBagSizer(0,0)
        usr_style = wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL

        text_location_and_bandwith = wx.StaticText(self,-1,u'LocationAndBandwith:',style=usr_style)
        sizer_main.Add(text_location_and_bandwith, pos=(0,0), span=(1,1), flag=usr_style)

        self.display_lab = wx.ComboBox(self,-1)
        sizer_main.Add(self.display_lab, pos=(0,1), span=(1,1), flag=usr_style)

        text_start_prb_index = wx.StaticText(self,-1,u'Start PRB Index:',style=usr_style)
        sizer_main.Add(text_start_prb_index, pos=(1,0), span=(1,1), flag=usr_style)

        self.start_prb_value = wx.TextCtrl(self,-1,u'',style=wx.TE_READONLY)
        sizer_main.Add(self.start_prb_value, pos=(1, 1), span=(1, 1), flag=usr_style)

        text_prb_length = wx.StaticText(self,-1,u'BandWith Length:',style=usr_style)
        sizer_main.Add(text_prb_length, pos=(2,0), span=(1,1), flag=usr_style)

        self.prb_length_value = wx.TextCtrl(self,-1,u'',style=wx.TE_READONLY)
        sizer_main.Add(self.prb_length_value, pos=(2, 1), span=(1, 1), flag=usr_style)

        b_cal_lab = wx.Button(self,-1,"Calculate BWP")
        self.Bind(wx.EVT_BUTTON,self.onbutton,b_cal_lab)
        sizer_main.Add(b_cal_lab, pos=(3, 0), span=(1, 1), flag=usr_style)
        self.equal = b_cal_lab

        b_del_lab = wx.Button(self,-1,"Clear BWP")
        self.Bind(wx.EVT_BUTTON,self.onbutton,b_del_lab)
        sizer_main.Add(b_del_lab, pos=(3, 1), span=(1, 1), flag=usr_style)
        self.equal = b_del_lab

        static_alloc_type_text = wx.StaticText(self,label='Alloc Type A or Type B')
        list_alloc_type = ['Type A','Type B']
        self.choice_alloc_type = wx.Choice(self,-1,choices = list_alloc_type)
        self.choice_alloc_type.SetSelection(0)
        sizer_main.Add(static_alloc_type_text, pos=(4, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_alloc_type, pos=(4, 1), span=(1, 1), flag=usr_style)

        text_sliv = wx.StaticText(self,-1,u'SLIV:',style=usr_style)
        sizer_main.Add(text_sliv, pos=(5,0), span=(1,1), flag=usr_style)

        self.display_sliv = wx.ComboBox(self,-1)
        sizer_main.Add(self.display_sliv, pos=(5,1), span=(1,1), flag=usr_style)

        text_start_symbol_index = wx.StaticText(self,-1,u'Start Symbol Index:',style=usr_style)
        sizer_main.Add(text_start_symbol_index, pos=(6,0), span=(1,1), flag=usr_style)

        self.start_symbol_value = wx.TextCtrl(self,-1,u'',style=wx.TE_READONLY)
        sizer_main.Add(self.start_symbol_value, pos=(6, 1), span=(1, 1), flag=usr_style)

        text_symbol_length = wx.StaticText(self,-1,u'Symbol Length:',style=usr_style)
        sizer_main.Add(text_symbol_length, pos=(7,0), span=(1,1), flag=usr_style)

        self.symbol_length_value = wx.TextCtrl(self,-1,u'',style=wx.TE_READONLY)
        sizer_main.Add(self.symbol_length_value, pos=(7, 1), span=(1, 1), flag=usr_style)

        b_cal_sliv = wx.Button(self,-1,"Calculate SLIV")
        self.Bind(wx.EVT_BUTTON,self.onbutton,b_cal_sliv)
        sizer_main.Add(b_cal_sliv, pos=(8, 0), span=(1, 1), flag=usr_style)
        self.equal = b_cal_sliv

        b_del_siiv = wx.Button(self,-1,"Clear SLIV")
        self.Bind(wx.EVT_BUTTON,self.onbutton,b_del_siiv)
        sizer_main.Add(b_del_siiv, pos=(8, 1), span=(1, 1), flag=usr_style)
        self.equal = b_del_siiv

        static_pxsch_text = wx.StaticText(self,label='PDSCH or PUSCH')
        list_pxsch = ['PDSCH','PUSCH']
        self.choice_pxsch = wx.Choice(self,-1,choices = list_pxsch)
        self.choice_pxsch.SetSelection(0)
        sizer_main.Add(static_pxsch_text, pos=(9, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_pxsch, pos=(9, 1), span=(1, 1), flag=usr_style)

        static_dmrs_typeA_pos_text = wx.StaticText(self,label='DMRS TypeA Pos')
        list_dmrs_typeA_pos = ['','pos2','pos3']
        self.choice_dmrs_typeA_pos = wx.Choice(self,-1,choices = list_dmrs_typeA_pos)
        self.choice_dmrs_typeA_pos.SetSelection(0)
        sizer_main.Add(static_dmrs_typeA_pos_text, pos=(10, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_dmrs_typeA_pos, pos=(10, 1), span=(1, 1), flag=usr_style)

        static_dmrs_type_text = wx.StaticText(self,label='DMRS Type 1 or Type 2')
        list_dmrs_type = ['Type 1','Type 2']
        self.choice_dmrs_type = wx.Choice(self,-1,choices = list_dmrs_type)
        self.choice_dmrs_type.SetSelection(0)
        sizer_main.Add(static_dmrs_type_text, pos=(11, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_dmrs_type, pos=(11, 1), span=(1, 1), flag=usr_style)

        static_dmrs_length_text = wx.StaticText(self,label='DMRS Length 1 or Length 2')
        list_dmrs_length = ['Length 1','Length 2']
        self.choice_dmrs_length = wx.Choice(self,-1,choices = list_dmrs_length)
        self.choice_dmrs_length.SetSelection(0)
        sizer_main.Add(static_dmrs_length_text, pos=(12, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_dmrs_length, pos=(12, 1), span=(1, 1), flag=usr_style)

        static_add_dmrs_pos_text = wx.StaticText(self,label='Add DMRS pos')
        list_add_dmrs_pos = ['','pos1','pos2','pos3']
        self.choice_add_dmrs_pos = wx.Choice(self,-1,choices = list_add_dmrs_pos)
        self.choice_add_dmrs_pos.SetSelection(0)
        sizer_main.Add(static_add_dmrs_pos_text, pos=(13, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_add_dmrs_pos, pos=(13, 1), span=(1, 1), flag=usr_style)

        static_pdcch_sym_text = wx.StaticText(self,label='PDCCH Symbol Number')
        list_pdcch_sym = ['','1 Symbol','2 Symbol']
        self.choice_pdcch_sym = wx.Choice(self,-1,choices = list_pdcch_sym)
        self.choice_pdcch_sym.SetSelection(0)
        sizer_main.Add(static_pdcch_sym_text, pos=(19, 0), span=(1, 1), flag=usr_style)
        sizer_main.Add(self.choice_pdcch_sym, pos=(19, 1), span=(1, 1), flag=usr_style)

        b_get_res_grid = wx.Button(self,-1,"Get Resource Grid")
        self.Bind(wx.EVT_BUTTON,self.onbutton,b_get_res_grid)
        sizer_main.Add(b_get_res_grid, pos=(20, 0), span=(1, 1), flag=usr_style)
        self.equal = b_get_res_grid

        self.SetSizer(sizer_main)
        sizer_main.Fit(self)
        self.CenterOnScreen()
Exemplo n.º 8
0
    total = F[0] * F[1] * F[3] / 1e9
    print("Rest:", rest, "G", "Total:", total, "G")
print(api.GetComputerName())
print(api.GetConsoleTitle())
print(api.GetCommandLine())
print(api.GetCursorPos())
print(api.GetDomainName())
print(api.GetEnvironmentVariable('path'))
print(api.GetFileAttributes('.'))
print(api.GetFileVersionInfo('C:\\windows\\system32\\cmd.exe', "\\"))
print(api.GetFullPathName('.'))
print(api.GetLocalTime())
print(api.GetLogicalDriveStrings().replace('\x00', ' '))
print(api.GetLogicalDrives())
print(api.GetLongPathName('C:'))
print(api.GetModuleFileName(0))
print(api.GetNativeSystemInfo())
print(hex(api.GetSysColor(con.COLOR_WINDOW)))
print(api.GetSystemDirectory())
print(api.GetSystemInfo())
print(api.GetSystemMetrics(con.SM_CXSCREEN))
print(api.GetSystemTime())
print(api.GetTickCount())
# print(api.GetTimeZoneInformation())
print(api.GetUserDefaultLangID())
print(api.GetUserName())
print(api.GetVersion())
print(api.GetVolumeInformation('C:'))
print(api.GetWindowsDirectory())
print(api.GlobalMemoryStatus())
print(api.MessageBeep())
Exemplo n.º 9
0
    try:
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name))
    except _winreg.error:
        try:
            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name))
        except _winreg.error:
            print "Could not find the existing '%s' module registered in the registry" % (mod_name,)
            usage_and_die(4)
    # Create the debug key.
    sub_key = _winreg.CreateKey(key, "Debug")
    _winreg.SetValue(sub_key, None, _winreg.REG_SZ, dll_name)
    print "Registered '%s' in the registry" % (dll_name,)

def _domodule(mod_name, release_mod_filename):
    path, fname = os.path.split(release_mod_filename)
    base, ext = os.path.splitext(fname)
    new_fname = base + "_d" + ext
    if _docopy(new_fname, path):
        _doregister( mod_name, os.path.abspath( os.path.join(path, new_fname) ) )

    
# First the main Python DLL.
path, fname = path, fname = os.path.split(win32api.GetModuleFileName(sys.dllhandle))
base, ext = os.path.splitext(fname)
_docopy(base + "_d" + ext, path)

# Then pythoncom and pywintypes.
_domodule("pythoncom", pythoncom.__file__)
_domodule("pywintypes", pywintypes.__file__)

print "System _d files were setup."
Exemplo n.º 10
0
from . import validators

__app_name__ = 'SMTP Tester'
__version_info__ = ('0', '1', '6')
__version__ = '.'.join(__version_info__)
__author__ = 'Michael Paul Thomas Conigliaro'
__author_email__ = 'mike [at] conigliaro [dot] org'
__artist__ = 'Mark James (Silk icons from famfamfam.com)'
__copyright__ = "(c) %s %s" % (time.strftime('%Y'), __author__)
__url__ = 'http://github.com/mconigliaro/%s' % ''.join(
    __app_name__.lower().split())
__description__ = 'A cross-platform graphical SMTP diagnostic tool'

if hasattr(sys, 'frozen'):
    import win32api
    APP_ICON = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
else:
    APP_ICON = os.path.normpath(
        os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data',
                     'smtptester.xpm'))

APP_CONFIG = 'smtptester'
APP_DEFAULT_WIDTH = 525
APP_DEFAULT_HEIGHT = 700

ERROR = '#cc0000'
WARNING = '#ff6633'
INFO = '#999999'
ACTION = '#0000ff'
RESULT = '#009900'
NOTSET = '#000000'
Exemplo n.º 11
0
import os
import os.path
import sys

import win32api
import win32process
import win32event
import win32job
import base64

if __name__=='__main__':
    if hasattr(sys, "frozen"):
        this_dir = os.path.dirname(win32api.GetModuleFileName(None))
    else:
        this_dir = os.path.dirname(os.path.abspath(sys.argv[0]))

    startup = win32process.STARTUPINFO()
    # FIXME: this arg quoting won't work with trailing slashes. See MSDN: CommandLineToArgvW
    (hProcess, hThread, processId, threadId) = win32process.CreateProcess(None, ' '.join(['"' + arg + '"' for arg in sys.argv[1:]]), None, None, True, win32process.CREATE_SUSPENDED | win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup)

    assert not win32job.IsProcessInJob(hProcess, None)

    hJob = win32job.CreateJobObject(None, "")
    extended_info = win32job.QueryInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation)
    extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK
    win32job.SetInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation, extended_info)
    win32job.AssignProcessToJobObject(hJob, hProcess)
    # n.b. intentionally leak hJob. Otherwise, when running on Windows Server 2008R2 SP1, AssignProcessToJobObject closes hJob (try !handle
    # in windbg before and after), and we crash with invalid handle in CloseHandle on exit
    hJob.Detach()
Exemplo n.º 12
0
    del wh, wk

elif os_name == 'posix':
    os_version = os.uname()[0]


def calc_unix_dirs():
    appdir = '%s-%s' % (app_name, version)
    ip = os.path.join('share', 'pixmaps', appdir)
    dp = os.path.join('share', 'doc', '')
    lp = os.path.join('share', 'locale')
    return ip, dp, lp


if is_frozen_exe:
    app_root = os.path.split(os.path.abspath(win32api.GetModuleFileName(0)))[0]
else:
    app_root = os.path.split(os.path.abspath(sys.argv[0]))[0]
doc_root = app_root
osx = False
if os.name == 'posix':
    if os.uname()[0] == "Darwin":
        doc_root = app_root = app_root.encode('utf8')
        if has_pyobjc:
            doc_root = NSBundle.mainBundle().resourcePath()
            osx = True
image_root = os.path.join(app_root, 'images')
locale_root = os.path.join(app_root, 'locale')

if not os.access(image_root, os.F_OK) or not os.access(locale_root, os.F_OK):
    # we guess that probably we are installed on *nix in this case
Exemplo n.º 13
0
    def __init__(self):
        wx.Frame.__init__(self,
                          parent=None,
                          id=-1,
                          title='wanghaiying',
                          size=(300, 170))
        exeName = \
            win32api.GetModuleFileName(win32api.GetModuleHandle(None))

        # icon=wx.Icon('bnb.ico',wx.BITMAP_TYPE_ANY)

        icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(self, -1)

        # sizer=wx.FlexGridSizer(rows=2,cols=2,hgap=20,vgap=0)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add((20, 10))
        sizer.Add(wx.StaticText(panel, -1, '1.select excel file'), 0,
                  wx.ALIGN_CENTER)

        # sizer.Add(wx.StaticText(panel,-1," "),0,0)

        mainsizer.Add(sizer, 0)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add((20, -1))
        t_e = wx.TextCtrl(panel, -1, '', size=(200, 20))
        sizer.Add(t_e, 0, 0)
        sizer.Add((10, -1))
        b1 = wx.Button(panel, -1, label='...', size=(30, 20))
        sizer.Add(b1, 0, 0)
        self.Bind(wx.EVT_BUTTON, self.OnClick, b1)
        self.p_e = t_e
        mainsizer.Add(sizer)
        mainsizer.Add((-1, 10))
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add((20, -1))
        sizer.Add(wx.StaticText(panel, -1, '2.select word file'), 0, 0)
        mainsizer.Add(sizer)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add((20, -1))

        # sizer.Add(wx.StaticText(panel,-1," "),0,0)

        t_w = wx.TextCtrl(panel, -1, '', size=(200, 20))
        sizer.Add(t_w, 0, 0)
        sizer.Add((10, -1))

        # sizer=wx.BoxSizer(wx.HORIZONTAL)

        b2 = wx.Button(panel, -1, label='...', size=(30, 20))
        sizer.Add(b2, 0, 0)

        self.Bind(wx.EVT_BUTTON, self.OnClick2, b2)
        self.p_w = t_w
        mainsizer.Add(sizer)
        mainsizer.Add((-1, 10))
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add((60, -1))
        b_s = wx.Button(panel, -1, label='start', size=(40, 20))
        sizer.Add(b_s, 0, 0)
        sizer.Add((40, -1))
        b_c = wx.Button(panel, -1, label='exit', size=(40, 20))
        sizer.Add(b_c, 0, 0)
        self.Bind(wx.EVT_BUTTON, self.OnStart, b_s)
        self.Bind(wx.EVT_BUTTON, self.OnClose, b_c)

        menubar = wx.MenuBar()
        menu1 = wx.Menu()
        menu1.Append(-1, '&New')
        menu1.Append(-1, '&Open')
        menu1.Append(-1, '&Save')
        menu1.AppendSeparator()
        exit = menu1.Append(-1, '&Quit\tCtrl+Q')
        menubar.Append(menu1, '&File')
        menu2 = wx.Menu()
        menu2.Append(-1, '&Undo')
        menu2.Append(-1, '&Cut')
        menu2.Append(-1, 'C&opy')
        menu2.Append(-1, '&Paste')
        menubar.Append(menu2, '&Edit')
        self.SetMenuBar(menubar)
        self.Bind(wx.EVT_MENU, self.OnClose, exit)
        mainsizer.Add(sizer)
        panel.SetSizer(mainsizer)
        mainsizer.Fit(panel)
        panel.Fit()
Exemplo n.º 14
0
def _enforce_association():
    INSTDIR, EXENAME = os.path.split(win32api.GetModuleFileName(0))
    if 'python' in EXENAME.lower():
        # oops, running the .py too lazy to make that work
        INSTDIR = r"C:\Program Files\BitTorrent"
        EXENAME = "bittorrent.exe"

    # owie
    edit_flags = chr(0x00) + chr(0x00) + chr(0x10) + chr(0x00)

    # lots of wrappers for more direct NSIS mapping
    HKCR = _winreg.HKEY_CLASSES_ROOT
    HKCU = _winreg.HKEY_CURRENT_USER

    def filter_vars(s):
        s = s.replace("$INSTDIR", INSTDIR)
        s = s.replace("${EXENAME}", EXENAME)
        return s

    def WriteReg(root_key, subkey, key_name, type, value):
        subkey = filter_vars(subkey)
        key_name = filter_vars(key_name)
        value = filter_vars(value)
        # CreateKey opens the key for us and creates it if it does not exist
        #key = _winreg.OpenKey(root_key, subkey, 0, _winreg.KEY_ALL_ACCESS)
        key = _winreg.CreateKey(root_key, subkey)
        _winreg.SetValueEx(key, key_name, 0, type, value)

    def WriteRegStr(root_key, subkey, key_name, value):
        WriteReg(root_key, subkey, key_name, _winreg.REG_SZ, value)

    def WriteRegBin(root_key, subkey, key_name, value):
        WriteReg(root_key, subkey, key_name, _winreg.REG_BINARY, value)

    def DeleteRegKey(root_key, subkey):
        try:
            _winreg.DeleteKey(root_key, subkey)
        except WindowsError:
            # key doesn't exist
            pass

    ## Begin NSIS copy/paste/translate

    WriteRegStr(HKCR, '.torrent', "", "bittorrent")
    DeleteRegKey(HKCR, r".torrent\Content Type")
    # This line maks it so that BT sticks around as an option
    # after installing some other default handler for torrent files
    WriteRegStr(HKCR, r".torrent\OpenWithProgids", "bittorrent", "")

    # this prevents user-preference from generating "Invalid Menu Handle" by looking for an app
    # that no longer exists, and instead points it at us.
    WriteRegStr(
        HKCU,
        r"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.torrent",
        "Application", EXENAME)
    WriteRegStr(HKCR, r"Applications\${EXENAME}\shell", "", "open")
    WriteRegStr(HKCR, r"Applications\${EXENAME}\shell\open\command", "",
                r'"$INSTDIR\${EXENAME}" "%1"')

    # Add a mime type
    WriteRegStr(HKCR, r"MIME\Database\Content Type\application/x-bittorrent",
                "Extension", ".torrent")

    # Add a shell command to match the 'bittorrent' handler described above
    WriteRegStr(HKCR, "bittorrent", "", "TORRENT File")

    WriteRegBin(HKCR, "bittorrent", "EditFlags", edit_flags)
    # make us the default handler for bittorrent://
    WriteRegBin(HKCR, "bittorrent", "URL Protocol", chr(0x0))
    WriteRegStr(HKCR, r"bittorrent\Content Type", "",
                "application/x-bittorrent")
    WriteRegStr(HKCR, r"bittorrent\DefaultIcon", "", r"$INSTDIR\${EXENAME},0")
    WriteRegStr(HKCR, r"bittorrent\shell", "", "open")

    ##    ReadRegStr $R1 HKCR "bittorrent\shell\open\command" ""
    ##    StrCmp $R1 "" continue
    ##
    ##    WriteRegStr HKCR "bittorrent\shell\open\command" "backup" $R1
    ##
    ##    continue:
    WriteRegStr(HKCR, r"bittorrent\shell\open\command", "",
                r'"$INSTDIR\${EXENAME}" "%1"')

    # Add a shell command to handle torrent:// stuff
    WriteRegStr(HKCR, "torrent", "", "TORRENT File")
    WriteRegBin(HKCR, "torrent", "EditFlags", edit_flags)
    # make us the default handler for torrent://
    WriteRegBin(HKCR, "torrent", "URL Protocol", chr(0x0))
    WriteRegStr(HKCR, r"torrent\Content Type", "", "application/x-bittorrent")
    WriteRegStr(HKCR, r"torrent\DefaultIcon", "", "$INSTDIR\${EXENAME},0")
    WriteRegStr(HKCR, r"torrent\shell", "", "open")

    ##    ReadRegStr $R1 HKCR "torrent\shell\open\command" ""
    ##    WriteRegStr HKCR "torrent\shell\open\command" "backup" $R1

    WriteRegStr(HKCR, r"torrent\shell\open\command", "",
                r'"$INSTDIR\${EXENAME}" "%1"')
Exemplo n.º 15
0
    def persist(self, persist):
        """Add/Remove persistence to reboots by adding a registry key entry which autoruns a vbs script on boot.

        The vbs script is required in order to run this component silently and is created/removed during this method.
        This method is automatically called to add persistence during initialisation and remove persistence during
        the kill routine.
        @param persist: whether to add or remove persistence
        """
        dir_name = os.path.dirname(os.path.abspath(__file__))
        vbs_script_file = os.path.join(dir_name, "data.vbs")
        if persist:
            if not os.path.exists(vbs_script_file):
                curr_file = win32api.GetModuleFileName(0)
                target_exe = os.path.basename(curr_file)
                if target_exe == "python.exe":
                    logging.debug(
                        "Running as python script, adding args to persistence script."
                    )
                    curr_file = win32api.GetCommandLine()
                vbs_script = open(vbs_script_file, "w")
                # Windows doesn't like it when something being executed using the autorun registry key being used here
                # modifies the registry, so the '-r' argument is passed to this script to disable the persistence
                # adding routine on bootup.
                vbs_script.write(
                    'Dim WShell\nSet WShell = CreateObject("Wscript.Shell")\nWShell.Run "{0} -r", 0\nSet WShell = Nothing'
                    .format(curr_file))  # nopep8
                vbs_script.close()
                startup_script = "wscript \"{0}\"".format(vbs_script_file)
                curr_script = None
                try:
                    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
                                                self.PERSISTENCE_KEY, 0,
                                                win32con.KEY_QUERY_VALUE)
                    curr_script = win32api.RegQueryValueEx(
                        key, self.REG_KEY_ENTRY)
                    win32api.RegCloseKey(key)
                except Exception as e:
                    logging.exception("Unhandled Exception: {0}".format(e))
                # if curr_script is None (no value) or incorrect, replace with correct one
                if startup_script != curr_script:
                    logging.debug(
                        "Adding {0} to run on startup...".format(curr_file))
                    logging.debug(
                        "Script executed by registry key on boot: {0}".format(
                            startup_script))
                    try:
                        key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
                                                    self.PERSISTENCE_KEY, 0,
                                                    win32con.KEY_SET_VALUE)
                        win32api.RegSetValueEx(key, self.REG_KEY_ENTRY, 0,
                                               win32con.REG_SZ,
                                               "{0}".format(startup_script))
                        win32api.RegCloseKey(key)
                    except Exception as e:
                        logging.exception("Unhandled Exception: {0}".format(e))
        else:
            logging.debug("Removing from startup...")
            if os.path.exists(vbs_script_file):
                logging.debug("Removing vbs script.")
                try:
                    os.remove(vbs_script_file)
                except Exception as e:
                    logging.exception("Unhandled Exception: {0}".format(e))
            try:
                key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
                                            self.PERSISTENCE_KEY, 0,
                                            win32con.KEY_SET_VALUE)
                win32api.RegDeleteValue(key, self.REG_KEY_ENTRY)
                win32api.RegCloseKey(key)
            except Exception as e:
                logging.exception("Unhandled Exception: {0}".format(e))
Exemplo n.º 16
0
        except winreg.error:
            print(
                "Could not find the existing '%s' module registered in the registry"
                % (mod_name, ))
            usage_and_die(4)
    # Create the debug key.
    sub_key = winreg.CreateKey(key, "Debug")
    winreg.SetValue(sub_key, None, winreg.REG_SZ, dll_name)
    print("Registered '%s' in the registry" % (dll_name, ))


def _domodule(mod_name, release_mod_filename):
    path, fname = os.path.split(release_mod_filename)
    base, ext = os.path.splitext(fname)
    new_fname = base + "_d" + ext
    if _docopy(new_fname, path):
        _doregister(mod_name, os.path.abspath(os.path.join(path, new_fname)))


# First the main Python DLL.
path, fname = path, fname = os.path.split(
    win32api.GetModuleFileName(sys.dllhandle))
base, ext = os.path.splitext(fname)
_docopy(base + "_d" + ext, path)

# Then pythoncom and pywintypes.
_domodule("pythoncom", pythoncom.__file__)
_domodule("pywintypes", pywintypes.__file__)

print("System _d files were setup.")
Exemplo n.º 17
0
    def __init__(self,
                 parent,
                 id=-1,
                 title="EasyAlarmer",
                 pos=wx.DefaultPosition,
                 size=(300, 400),
                 style=wx.CAPTION | wx.MINIMIZE_BOX | wx.CLOSE_BOX
                 | wx.SYSTEM_MENU | wx.FRAME_NO_TASKBAR | wx.STAY_ON_TOP):
        #style =wx.FRAME_SHAPED | wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR | wx.STAY_ON_TOP ) :

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        #self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_ICONIZE, self.OnIconfiy)

        #SysTray Icon Setup
        if hasattr(sys, "frozen") and getattr(sys, "frozen") == "windows_exe":
            exeName = win32api.GetModuleFileName(
                win32api.GetModuleHandle(None))
            self.tbIcon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        else:
            self.tbIcon = wx.Icon("EasyAlarmer.ico", wx.BITMAP_TYPE_ICO)

        self.tb = wx.TaskBarIcon()
        self.tb.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnTaskBarRightClick)

        self.SetIcon(self.tbIcon)

        self.tb.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnShow)

        wx.EVT_MENU(self.tb, TB_SHOW, self.OnShow)
        wx.EVT_MENU(self.tb, TB_CLOSE, self.OnExit)

        #Setup Timer and TimerList
        self.LastClockTime = wx.DateTime_Now()
        self.ClockInterval = 1
        self.AlamerList = list()

        self.Bind(wx.EVT_TIMER, self.OnTimer)
        self.Timer = wx.Timer(self, -1)
        self.Timer.Start(self.ClockInterval * 1000)

        # Create Panel and Buttons
        panel = wx.Panel(self, size=(300, 30))
        panel_sizer = wx.BoxSizer(wx.HORIZONTAL)
        panel_sizer.SetMinSize((300, 40))

        self.AddBtn = wx.Button(panel, -1, u"添加")
        self.EditBtn = wx.Button(panel, -1, u"修改")
        self.DelBtn = wx.Button(panel, -1, u"删除")

        self.Bind(wx.EVT_BUTTON, self.OnAddAlarmItem, self.AddBtn)
        self.Bind(wx.EVT_BUTTON, self.OnEditAlarmItem, self.EditBtn)
        self.Bind(wx.EVT_BUTTON, self.OnDelAlarmItem, self.DelBtn)

        #panel_sizer.AddSpacer(80,10)
        panel_sizer.Add(self.AddBtn, 1, wx.ALL | wx.EXPAND, 5)
        panel_sizer.Add(self.EditBtn, 1, wx.ALL | wx.EXPAND, 5)
        panel_sizer.Add(self.DelBtn, 1, wx.ALL | wx.EXPAND, 5)
        panel.SetSizer(panel_sizer)
        panel.Layout()

        #Create Panel and  Analog Clock
        clockPanel = wx.Panel(self, size=(300, 300))
        clockPanelSizer = wx.BoxSizer(wx.HORIZONTAL)
        clockPanelSizer.SetMinSize((300, 300))
        self.clock = ac.AnalogClock(clockPanel, size=(250,250), hoursStyle = ac.TICKS_DECIMAL,clockStyle=ac.SHOW_HOURS_TICKS| \
                                                 ac.SHOW_HOURS_HAND| \
                                                 ac.SHOW_MINUTES_HAND| \
                   ac.SHOW_SECONDS_HAND| \
                                                 ac.SHOW_SHADOWS)
        colour = wx.Colour(128, 0, 0)
        self.clock.SetHandFillColour(colour)
        colour = wx.Colour(179, 0, 89)
        self.clock.SetHandBorderColour(colour)
        self.clock.SetTickFillColour(colour)
        self.clock.SetTickBorderColour(colour)
        #colour = wx.Colour(225, 255, 255)
        #self.clock.SetFaceBorderColour(colour)
        #self.clock.SetBackgroundColour(colour)
        colour = wx.Colour(249, 255, 255)
        self.clock.SetFaceFillColour(colour)
        colour = wx.Colour(255, 213, 213)
        self.clock.SetShadowColour(colour)
        self.clock.SetTickFont(
            wx.Font(10, wx.FONTFAMILY_ROMAN, wx.NORMAL, wx.BOLD))

        clockPanelSizer.Add(self.clock, 0, wx.ALL, 25)

        #Create AlarmListCtrl
        self.list = AlarmerListCtrl(self,
                                    -1,
                                    size=(300, 150),
                                    style=wx.LC_REPORT)
        self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnEditAlarmItem, self.list)
        self.list.PopulateList()

        # Use a sizer to layout the controls, stacked vertically and with
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(clockPanelSizer, 0, wx.ALL, 0)
        sizer.Add(self.list, 0, wx.ALL, 0)
        sizer.Add(panel, 0, wx.ALL, 0)
        self.SetSizerAndFit(sizer)

        width, height = self.GetSizeTuple()
        dispSize = wx.GetClientDisplayRect()
        newPos = wx.Point()
        newPos.x = dispSize.width - width - 1
        newPos.y = (dispSize.height - height) / 2
        self.SetPosition(newPos)
Exemplo n.º 18
0
    def init(self):
        """
    @return  bool
    @raise
    """
        # Get DLL location
        dllHandle = self.dll._handle  # DWORD module
        dllPath = win32api.GetModuleFileName(dllHandle)
        appDir = os.path.dirname(dllPath)  # TransCAT location

        appDir = self._normalizeDirPath(appDir)

        tempDir = self.tempDir
        if not tempDir:
            tempDir = ''
        else:
            if not os.path.exists(tempDir):
                os.makedirs(tempDir)
            tempDir = self._normalizeDirPath(tempDir)

        # Import needed Windows functions
        kernel32 = ctypes.windll.kernel32
        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 4  # not exist in win32con
        GetModuleHandleExA = kernel32.GetModuleHandleExA
        VirtualProtect = kernel32.VirtualProtect

        pFuncAddr = win32api.GetProcAddress(dllHandle, "GSetJK_ITEngineEx")
        hModule = ctypes.c_long(0)
        GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, pFuncAddr,
                           ctypes.byref(hModule))
        hModule = hModule.value  # convert to C long type

        # Hack dll memory or it will raise illegal access to 0xeb error
        EDIT_CODE = 0xeb
        for offset, permission in (
            (0xfc80, win32con.PAGE_READWRITE),
            (0xfc98, win32con.PAGE_EXECUTE_READWRITE),
        ):
            dwOldProtect = ctypes.c_long(0)
            VirtualProtect(hModule + offset, 1, permission,
                           ctypes.byref(dwOldProtect))
            ctypes.memset(hModule + offset, EDIT_CODE, 1)
            dwTmpProtect = ctypes.c_long(0)
            VirtualProtect(hModule + offset, 1, dwOldProtect,
                           ctypes.byref(dwTmpProtect))

        # *_PJK files must be in a directory where VNR always have read/write permission
        # By default, TransCAT is installed to ProgramFiles which require admin privilege to modify.

        dll = self.dll

        dll.GSetJK_gdDir(
            1, appDir)  # optional if it is the same as the current directory
        dll.GSetJK_gdTempGenbun(
            1, tempDir +
            "GENBUN_PJK")  # VNR must have read/write access to this temp file
        dll.GSetJK_gdTempTerget(
            1, tempDir +
            "TERGET_PJK")  # VNR must have read/write access to this temp file
        dll.GSetJK_gdTempMorph(
            1, tempDir +
            "MORPH_PJK")  # VNR must have read/write access to this temp file
        dll.GSetJK_gdTempChnGen(
            1, tempDir +
            "KRNGEN_PJK")  # VNR must have read/write access to this temp file
        dll.GSetJK_gQUESTIONMARK(1, 0)
        dll.GSetJK_gEXCLAMATION(1, 0)
        dll.GSetJK_gSEMICOLONMARK(1, 0)
        dll.GSetJK_gCOLONMARK(1, 0)
        dll.GSetJK_gdChudanFlag(0, 0)
        dll.GSetJK_gdUseShiftJisCode(1, 1)
        dll.GSetJK_gdDdeSpaceCut(1, 0)
        dll.GSetJK_gnDdeTransFlag(1, 0)
        dll.GSetJK_gdFileTransFlag(1, 0)
        dll.GSetJK_gdLineFlag(1, 2)
        dll.GSetJK_gdLineLength(1, 48)
        dll.GSetJK_gdPeriodOnly(1, 0)
        dll.GSetJK_gdUseGairaiFlag(1, 0)
        dll.GSetJK_gdUseKanjiFlag(1, 1)
        dll.GSetJK_gbUnDDE(1, 0)

        dll.ControlJK_UserDic(1)
        dll.GSetJK_UserDicInit()

        s = ''  # char s[1] = {'0'};
        res = dll.GSetJK_ITEngineEx(s, s)
        ok = res == 1
        return ok
Exemplo n.º 19
0
of the GNU General Public License, incorporated herein by reference.
"""

# This version of config.py is used in the binary installer
# distributions of TortoiseHg on Windows.  Since we no longer need to
# worry about Python shell extensions, we can use the path of the
# current executable to find our package data.

import os
import sys
import win32api, win32process

proc = win32api.GetCurrentProcess()
try:
    # This will fail on windows < NT
    procpath = win32process.GetModuleFileNameEx(proc, 0)
except:
    procpath = win32api.GetModuleFileName(0)

bin_path = os.path.dirname(procpath)
license_path = os.path.join(bin_path, 'COPYING.txt')
locale_path = os.path.join(bin_path, 'locale')
icon_path = os.path.join(bin_path, 'icons')

enc = sys.getfilesystemencoding()
if enc:
    bin_path = bin_path.encode(enc)
    license_path = license_path.encode(enc)
    locale_path = locale_path.encode(enc)
    icon_path = icon_path.encode(enc)
Exemplo n.º 20
0
    def __init__(self):
        """构造函数"""

        style = wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.SIMPLE_BORDER
        wx.Frame.__init__(self,
                          parent=None,
                          id=-1,
                          title=APP_TITLE,
                          style=style)

        self.SetBackgroundColour((217, 228, 241))  # 设置窗口背景色
        self.SetSize((287, 283))  # 设置窗口大小
        self.Center()  # 设置窗口屏幕居中

        if hasattr(sys, "frozen") and getattr(
                sys, "frozen") == "windows_exe":  # 如果打包成exe文件,运行时执行此处代码
            exeName = win32api.GetModuleFileName(
                win32api.GetModuleHandle(None))  # 此处用到win32api模块
            icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)  # 读图标文件
        else:  # 若以源码方式运行,则执行此处代码
            icon = wx.Icon(APP_ICON, wx.BITMAP_TYPE_ICO)  # 读图标文件
        self.SetIcon(icon)  # 设置图标

        # 用输入框控件作为计算器屏幕,设置为只读(wx.TE_READONLY)和右齐(wx.ALIGN_RIGHT)
        self.screen = wx.TextCtrl(self,
                                  -1,
                                  '',
                                  pos=(10, 10),
                                  size=(252, 45),
                                  style=wx.TE_READONLY | wx.ALIGN_RIGHT)
        self.screen.SetFont(
            wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False,
                    '微软雅黑'))  # 设置字体字号
        self.screen.SetBackgroundColour((0, 0, 0))  # 设置屏幕背景色
        self.screen.SetForegroundColour((0, 255, 0))  # 设置屏幕前景色

        # 按键布局参数
        btn_size = (60, 30)  # 定义按键的尺寸,便于统一修改
        x0, y0 = (10, 65)  # 定义按键区域的相对位置
        dx, dy = (64, 34)  # 定义水平步长和垂直步长

        # 定义按键排列顺序和名称
        allKeys = [['(', ')', 'Back', 'Clear'], ['7', '8', '9', '/'],
                   ['4', '5', '6', '*'], ['1', '2', '3', '-'],
                   ['0', '.', '=', '+']]

        # 指定每个按键声音的频率,523赫兹就是C调中音
        self.keySound = {
            '(': 392,
            ')': 440,
            '0': 494,
            '1': 523,
            '2': 587,
            '3': 659,
            '4': 698,
            '5': 784,
            '6': 880,
            '7': 988,
            '8': 1047,
            '9': 1175,
            '.': 1318,
            '+': 523,
            '-': 587,
            '*': 659,
            '/': 698,
            'Clear': 784,
            'Back': 880,
            '=': 2000
        }

        # 生成所有按键
        for i in range(len(allKeys)):
            for j in range(len(allKeys[i])):
                # 添加按钮。请注意属性name的用法
                #btn_ = wx.Button(self, -1, allKeys[i][j], pos=(x0+j*dx, y0+i*dy), size=btn_size, name=allKeys[i][j])

                key = allKeys[i][j]
                btn = wxbtn.GenButton(self,
                                      -1,
                                      key,
                                      pos=(x0 + j * dx, y0 + i * dy),
                                      size=btn_size,
                                      name=key)
                if key in [
                        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'
                ]:
                    btn.SetBezelWidth(1)  # 设置3D效果
                    btn.SetBackgroundColour(wx.Colour(217, 228,
                                                      241))  # 定义按键的背景色
                elif key in ['(', ')', 'Back', 'Clear']:
                    btn.SetBezelWidth(2)
                    btn.SetBackgroundColour(wx.Colour(217, 220, 235))
                    btn.SetForegroundColour(wx.Colour(224, 60, 60))
                elif key in ['+', '-', '*', '/']:
                    btn.SetBezelWidth(2)
                    btn.SetBackgroundColour(wx.Colour(246, 225, 208))
                    btn.SetForegroundColour(wx.Colour(60, 60, 224))
                else:
                    btn.SetBezelWidth(2)
                    btn.SetBackgroundColour(wx.Colour(245, 227, 129))
                    btn.SetForegroundColour(wx.Colour(60, 60, 224))
                    btn.SetToolTip(u"显示计算结果")

        # 绑定按钮事件(请注意:既非弹起,也不是按下,是按钮被点击)
        self.Bind(wx.EVT_BUTTON, self.onButton)  # 将按钮事件绑定在所有按钮上
Exemplo n.º 21
0
def get_module_filename():
    if is_frozen_exe:
        return os.path.abspath(win32api.GetModuleFileName(0))
    else:
        return os.path.abspath(sys.argv[0])
Exemplo n.º 22
0
    def __init__(self, parent, title):
        self.dirname = ''
        #队列用于线程间传递消息
        self.queue = queue.Queue()
        #终止消息队列用于线程间传递终止消息
        self.abortQueue = queue.Queue()
        #保存目录数量
        self.result = 0
        super(Mywin, self).__init__(parent, title=title, size=(800, 800))
        # A Statusbar in the bottom of the window
        self.CreateStatusBar()
        self.SetStatusText(u"生成PDF书签")

        # 用于从module中读取ico,避免了要在程序所在路径附上此ico
        exeName = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
        icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        # Setting up the menu. file menu
        file_menu = wx.Menu()
        file_menu_open = file_menu.Append(wx.ID_OPEN, u"&导出目录",
                                          " 导出含目录PDF中的目录为txt格式")
        file_menu_about = file_menu.Append(wx.ID_ABOUT, u"&关于",
                                           " 由sweeney_he制作")
        file_menu_exit = file_menu.Append(wx.ID_EXIT, u"&退出", " 退出程序")

        # # Setting up the menu. tool menu
        # self.tool_menu = wx.Menu()
        # tool_menu_auto = tool_menu.Append(wx.ID_FILE1, u"&自动模式", " 输入目录位置,自动识别生成目录")
        # tool_menu_manul = tool_menu.Append(wx.ID_FILE2, u"&手动模式", " 已有目录数据,选择目录txt文件")

        # Creating the menubar
        self.menuBar = wx.MenuBar()
        #---file
        self.menuBar.Append(file_menu,
                            u"&文件")  # Adding the "filemenu" to the MenuBar
        # #---tool
        # self.menuBar.Append(self.tool_menu, u"&已获取目录")  # Adding the "filemenu" to the MenuBar

        self.SetMenuBar(
            self.menuBar)  # Adding the MenuBar to the Frame content.

        #面板
        panel = wx.Panel(self)
        #总体排版器
        vbox = wx.BoxSizer(wx.VERTICAL)

        # #页面范围布局
        # nm = wx.StaticBox(panel, -1, 'PDF中目录所在页的范围:')
        # nmSizer = wx.StaticBoxSizer(nm, wx.VERTICAL)
        #
        # nmbox = wx.BoxSizer(wx.HORIZONTAL)
        # fn = wx.StaticText(panel, -1, "真实页数:  ")
        #
        # nmbox.Add(fn, 0, wx.ALL | wx.CENTER, 2)
        # nm1 = wx.TextCtrl(panel, -1, style=wx.ALIGN_LEFT,size=(50,25))
        # nm2 = wx.TextCtrl(panel, -1, style=wx.ALIGN_LEFT,size=(50,25))
        # ln = wx.StaticText(panel, -1, "—")
        #
        # nmbox.Add(nm1, 0, wx.ALL | wx.CENTER, 2)
        # nmbox.Add(ln, 0, wx.ALL | wx.CENTER, 2)
        # nmbox.Add(nm2, 0, wx.ALL | wx.CENTER, 2)
        # nmSizer.Add(nmbox, 0, wx.ALL | wx.CENTER, 20)

        #第一层并列两个区域
        topSizer = wx.BoxSizer(wx.HORIZONTAL)
        """"=============页面偏移选择区域============="""
        nm1 = wx.StaticBox(panel, -1, u'信息与确认:')
        nmSizer1 = wx.StaticBoxSizer(nm1, wx.VERTICAL)

        nmbox1 = wx.BoxSizer(wx.HORIZONTAL)
        fn1 = wx.StaticText(panel, -1, u" 目录与实际PDF页数偏移: ")

        nmbox1.Add(fn1, 0, wx.ALL | wx.CENTER, 2)
        self.offset = wx.TextCtrl(panel,
                                  -1,
                                  style=wx.ALIGN_LEFT,
                                  size=(50, 25))
        run_button = wx.Button(panel, -1, u'运行')

        nmbox1.Add(self.offset, 0, wx.ALL | wx.CENTER, 10)
        nmbox1.Add(run_button, 0, wx.ALL | wx.CENTER, 10)
        nmSizer1.Add(nmbox1, 0, wx.ALL | wx.CENTER, 10)
        """"=============在线搜索目录区域============="""
        nm2 = wx.StaticBox(panel, -1, u'在线搜索目录:')
        numSizer2 = wx.StaticBoxSizer(nm2, wx.VERTICAL)

        nmbox2 = wx.BoxSizer(wx.HORIZONTAL)
        fn2 = wx.StaticText(panel, -1, u" 书籍ISBN/名称: ")

        nmbox2.Add(fn2, 0, wx.ALL | wx.CENTER, 2)
        self.isbn_area = wx.TextCtrl(panel,
                                     -1,
                                     style=wx.ALIGN_LEFT,
                                     size=(170, 25))
        search_button = wx.Button(panel, -1, u'搜索')

        nmbox2.Add(self.isbn_area, 0, wx.ALL | wx.CENTER, 10)
        nmbox2.Add(search_button, 0, wx.ALL | wx.CENTER, 10)
        numSizer2.Add(nmbox2, 0, wx.ALL | wx.CENTER, 10)

        topSizer.Add(nmSizer1, 0, wx.ALL, 2)
        topSizer.Add(numSizer2, 0, wx.ALL, 2)
        """"=============PDF路径选择区域============="""
        sbox1 = wx.StaticBox(panel, -1, u'选择PDF:')
        sbox1Sizer = wx.StaticBoxSizer(sbox1, wx.VERTICAL)

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        self.pdf_path_text = wx.TextCtrl(panel,
                                         -1,
                                         style=wx.ALIGN_LEFT,
                                         size=(610, 25))

        hbox.Add(self.pdf_path_text, 0, wx.ALL | wx.CENTER, 10)
        chooseFile_button1 = wx.Button(panel, -1, u'选择PDF')

        hbox.Add(chooseFile_button1, 0, wx.ALL | wx.CENTER, 10)

        sbox1Sizer.Add(hbox, 0, wx.ALL | wx.CENTER, 10)
        """"=============txt目录文件路径选择区域============="""
        sbox2 = wx.StaticBox(panel, -1, u'选择目录文件(txt格式):')
        sbox2Sizer = wx.StaticBoxSizer(sbox2, wx.VERTICAL)

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        self.txt_path_text = wx.TextCtrl(panel,
                                         -1,
                                         style=wx.ALIGN_LEFT,
                                         size=(610, 25))

        hbox.Add(self.txt_path_text, 0, wx.ALL | wx.CENTER, 10)
        chooseFile_button2 = wx.Button(panel, -1, u'选择目录')

        hbox.Add(chooseFile_button2, 0, wx.ALL | wx.CENTER, 10)

        sbox2Sizer.Add(hbox, 0, wx.ALL | wx.CENTER, 10)
        """===================目录编辑区域==================="""
        textbox = wx.StaticBox(panel, -1, u'编辑目录(自动同步到原TXT中):')
        textboxSizer = wx.StaticBoxSizer(textbox, wx.VERTICAL)

        text_in_box = wx.BoxSizer(wx.HORIZONTAL)
        #编辑区域
        self.txt_content_area = wx.TextCtrl(panel,
                                            -1,
                                            style=wx.TE_MULTILINE
                                            | wx.ALIGN_LEFT,
                                            size=(2000, 600))
        font = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'微软雅黑')
        self.txt_content_area.SetFont(font)

        text_in_box.Add(self.txt_content_area, 0, wx.ALL | wx.LEFT, 1)
        textboxSizer.Add(text_in_box, 0, wx.ALL | wx.LEFT, 1)

        #sbox1Sizer、sbox2Sizer加入vbox排版器
        vbox.Add(topSizer, 0, wx.ALL | wx.CENTER, 5)
        vbox.Add(sbox1Sizer, 0, wx.ALL | wx.CENTER, 5)
        vbox.Add(sbox2Sizer, 0, wx.ALL | wx.CENTER, 5)
        vbox.Add(textboxSizer, 0, wx.ALL | wx.CENTER, 5)

        #panel设置排版器
        panel.SetSizer(vbox)

        #收尾工作
        self.Centre()
        panel.Fit()
        """"=================绑定事件区域=================="""
        # files menu bind Events.
        self.Bind(wx.EVT_MENU, self.OnOpen, file_menu_open)
        self.Bind(wx.EVT_MENU, self.OnExit, file_menu_exit)
        self.Bind(wx.EVT_MENU, self.OnAbout, file_menu_about)

        # tools menu bind Events
        # self.Bind(wx.EVT_MENU, self.on_tool_menu_auto, self.tool_menu_auto)
        # self.Bind(wx.EVT_MENU, self.on_tool_menu_manul, self.tool_menu_manul)

        # 选择文件按钮绑定
        self.Bind(wx.EVT_BUTTON, self.on_chooseFile_button1,
                  chooseFile_button1)
        self.Bind(wx.EVT_BUTTON, self.on_chooseFile_button2,
                  chooseFile_button2)

        #运行按钮绑定
        self.Bind(wx.EVT_BUTTON, self.on_runButton, run_button)

        # 搜索目录按钮
        self.Bind(wx.EVT_BUTTON, self.on_search_button, search_button)

        #编辑区域失去焦点绑定
        #注意这种非命令事件的绑定方法
        self.txt_content_area.Bind(wx.EVT_KILL_FOCUS, self.onKillFocus)
        #self.txt_content_area.Bind(wx.EVT_SET_FOCUS,self.onGetFocus)

        self.Show()
Exemplo n.º 23
0
 def testHost(self):
     file = win32api.GetFullPathName(os.path.join(win32com.axscript.__path__[0], "test\\testHost.py"))
     cmd = '%s "%s"' % (win32api.GetModuleFileName(0), file)
     if verbose:
         print "Testing Python Scripting host"
     win32com.test.util.ExecuteShellCommand(cmd, self)
Exemplo n.º 24
0
            StartupInfo)
        # normally, we would save the pid etc. here...

        # Child is launched. Close the parents copy of those pipe handles
        # that only the child should have open.
        # You need to make sure that no handles to the write end of the
        # output pipe are maintained in this process or else the pipe will
        # not close when the child process exits and the ReadFile will hang.
        win32file.CloseHandle(hStderr_w)
        win32file.CloseHandle(hStdout_w)
        win32file.CloseHandle(hStdin_r)

        self.stdin = os.fdopen(msvcrt.open_osfhandle(self.hStdin_w, 0), "wb")
        self.stdin.write('hmmmmm\r\n')
        self.stdin.flush()
        self.stdin.close()

        self.stdout = os.fdopen(msvcrt.open_osfhandle(self.hStdout_r, 0), "rb")
        print("Read on stdout: ", repr(self.stdout.read()))

        self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb")
        print("Read on stderr: ", repr(self.stderr.read()))


if __name__ == '__main__':
    p = Process()
    exe = win32api.GetModuleFileName(0)
    p.run(exe + ' cat.py')

# end of runproc.py
Exemplo n.º 25
0
def GetIcon():
    exeName = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
    Icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
    return Icon
Exemplo n.º 26
0
    def __init__(self, parent):
        '''构造函数'''

        wx.Frame.__init__(self, parent, -1, APP_TITLE)
        self.SetBackgroundColour(wx.Colour(224, 224, 224))
        self.SetSize((520, 220))
        self.Center()

        if hasattr(sys, "frozen") and getattr(sys, "frozen") == "windows_exe":
            exeName = win32api.GetModuleFileName(
                win32api.GetModuleHandle(None))
            icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        else:
            icon = wx.Icon(APP_ICON, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        wx.StaticText(self,
                      -1,
                      u'第一行输入框:',
                      pos=(40, 50),
                      size=(100, -1),
                      style=wx.ALIGN_RIGHT)
        wx.StaticText(self,
                      -1,
                      u'第二行输入框:',
                      pos=(40, 80),
                      size=(100, -1),
                      style=wx.ALIGN_RIGHT)
        self.tip = wx.StaticText(self,
                                 -1,
                                 u'',
                                 pos=(145, 110),
                                 size=(150, -1),
                                 style=wx.ST_NO_AUTORESIZE)

        self.tc1 = wx.TextCtrl(self,
                               -1,
                               '',
                               pos=(145, 50),
                               size=(150, -1),
                               name='TC01',
                               style=wx.TE_CENTER)
        self.tc2 = wx.TextCtrl(self,
                               -1,
                               '',
                               pos=(145, 80),
                               size=(150, -1),
                               name='TC02',
                               style=wx.TE_PASSWORD | wx.ALIGN_RIGHT)

        btn_mea = wx.Button(self, -1, u'鼠标左键事件', pos=(350, 50), size=(100, 25))
        btn_meb = wx.Button(self, -1, u'鼠标所有事件', pos=(350, 80), size=(100, 25))
        btn_close = wx.Button(self,
                              -1,
                              u'关闭窗口',
                              pos=(350, 110),
                              size=(100, 25))

        # 控件事件
        self.tc1.Bind(wx.EVT_TEXT, self.EvtText)
        self.tc2.Bind(wx.EVT_TEXT, self.EvtText)
        self.Bind(wx.EVT_BUTTON, self.OnClose, btn_close)

        # 鼠标事件
        btn_mea.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        btn_mea.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        btn_mea.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
        btn_meb.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)

        # 键盘事件
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

        # 系统事件
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_SIZE, self.On_size)
Exemplo n.º 27
0
    python setup.py build install

"""

import sys

from distutils.core import setup
from distutils.extension import Extension
from distutils import sysconfig

# setup extra compilation and linking args
extraLinkArgs = ["-s"]
if sys.platform == "win32":
    import win32api
    extraLinkArgs.append("-Wl,--add-stdcall-alias")
    extraLinkArgs.append(win32api.GetModuleFileName(sys.dllhandle))

# define the list of files to be included as documentation for Windows
dataFiles = None
if sys.platform in ("win32", "cygwin"):
    baseName = "cx_imagediff-doc"
    dataFiles = [(baseName, ["LICENSE.TXT", "README.TXT"])]
    allFiles = []
    for fileName in open("MANIFEST").readlines():
        allFiles.append(fileName.strip())
    for dir in ["html"]:
        files = []
        for name in allFiles:
            if name.startswith(dir):
                files.append(name)
        dataFiles.append(("%s/%s" % (baseName, dir), files))
Exemplo n.º 28
0
def RegisterServer(
    clsid,
    pythonInstString=None,
    desc=None,
    progID=None,
    verProgID=None,
    defIcon=None,
    threadingModel="both",
    policy=None,
    catids=[],
    other={},
    addPyComCat=None,
    dispatcher=None,
    clsctx=None,
    addnPath=None,
):
    """Registers a Python object as a COM Server.  This enters almost all necessary
     information in the system registry, allowing COM to use the object.

     clsid -- The (unique) CLSID of the server.
     pythonInstString -- A string holding the instance name that will be created
                   whenever COM requests a new object.
     desc -- The description of the COM object.
     progID -- The user name of this object (eg, Word.Document)
     verProgId -- The user name of this version's implementation (eg Word.6.Document)
     defIcon -- The default icon for the object.
     threadingModel -- The threading model this object supports.
     policy -- The policy to use when creating this object.
     catids -- A list of category ID's this object belongs in.
     other -- A dictionary of extra items to be registered.
     addPyComCat -- A flag indicating if the object should be added to the list
              of Python servers installed on the machine.  If None (the default)
              then it will be registered when running from python source, but
              not registered if running in a frozen environment.
     dispatcher -- The dispatcher to use when creating this object.
     clsctx -- One of the CLSCTX_* constants.
     addnPath -- An additional path the COM framework will add to sys.path
                 before attempting to create the object.
  """

    ### backwards-compat check
    ### Certain policies do not require a "class name", just the policy itself.
    if not pythonInstString and not policy:
        raise TypeError(
            'You must specify either the Python Class or Python Policy which implement the COM object.'
        )

    keyNameRoot = "CLSID\\%s" % str(clsid)
    _set_string(keyNameRoot, desc)

    # Also register as an "Application" so DCOM etc all see us.
    _set_string("AppID\\%s" % clsid, progID)
    # Depending on contexts requested, register the specified server type.
    # Set default clsctx.
    if not clsctx:
        clsctx = pythoncom.CLSCTX_INPROC_SERVER | pythoncom.CLSCTX_LOCAL_SERVER
    # And if we are frozen, ignore the ones that don't make sense in this
    # context.
    if pythoncom.frozen:
        assert sys.frozen, "pythoncom is frozen, but sys.frozen is not set - don't know the context!"
        if sys.frozen == "dll":
            clsctx = clsctx & pythoncom.CLSCTX_INPROC_SERVER
        else:
            clsctx = clsctx & pythoncom.CLSCTX_LOCAL_SERVER
    # Now setup based on the clsctx left over.
    if clsctx & pythoncom.CLSCTX_INPROC_SERVER:
        # get the module to use for registration.
        # nod to Gordon's installer - if sys.frozen and sys.frozendllhandle
        # exist, then we are being registered via a DLL - use this DLL as the
        # file name.
        if pythoncom.frozen:
            if hasattr(sys, "frozendllhandle"):
                dllName = win32api.GetModuleFileName(sys.frozendllhandle)
            else:
                raise RuntimeError(
                    "We appear to have a frozen DLL, but I don't know the DLL to use"
                )
        else:
            # Normal case - running from .py file, so register pythoncom's DLL.
            dllName = os.path.basename(pythoncom.__file__)

        _set_subkeys(keyNameRoot + "\\InprocServer32", {
            None: dllName,
            "ThreadingModel": threadingModel,
        })
    else:  # Remove any old InProcServer32 registrations
        _remove_key(keyNameRoot + "\\InprocServer32")

    if clsctx & pythoncom.CLSCTX_LOCAL_SERVER:
        if pythoncom.frozen:
            # If we are frozen, we write "{exe} /Automate", just
            # like "normal" .EXEs do
            exeName = win32api.GetShortPathName(sys.executable)
            command = '%s /Automate' % (exeName, )
        else:
            # Running from .py sources - we need to write
            # 'python.exe win32com\server\localserver.py {clsid}"
            exeName = _find_localserver_exe(1)
            exeName = win32api.GetShortPathName(exeName)
            pyfile = _find_localserver_module()
            command = '%s "%s" %s' % (exeName, pyfile, str(clsid))
        _set_string(keyNameRoot + '\\LocalServer32', command)
    else:  # Remove any old LocalServer32 registrations
        _remove_key(keyNameRoot + "\\LocalServer32")

    if pythonInstString:
        _set_string(keyNameRoot + '\\PythonCOM', pythonInstString)
    else:
        _remove_key(keyNameRoot + '\\PythonCOM')
    if policy:
        _set_string(keyNameRoot + '\\PythonCOMPolicy', policy)
    else:
        _remove_key(keyNameRoot + '\\PythonCOMPolicy')

    if dispatcher:
        _set_string(keyNameRoot + '\\PythonCOMDispatcher', dispatcher)
    else:
        _remove_key(keyNameRoot + '\\PythonCOMDispatcher')

    if defIcon:
        _set_string(keyNameRoot + '\\DefaultIcon', defIcon)
    else:
        _remove_key(keyNameRoot + '\\DefaultIcon')

    if addnPath:
        _set_string(keyNameRoot + "\\PythonCOMPath", addnPath)
    else:
        _remove_key(keyNameRoot + "\\PythonCOMPath")

    if addPyComCat is None:
        addPyComCat = pythoncom.frozen == 0
    if addPyComCat:
        catids = catids + [CATID_PythonCOMServer]

    # Set up the implemented categories
    if catids:
        regCat = _cat_registrar()
        regCat.RegisterClassImplCategories(clsid, catids)

    # set up any other reg values they might have
    if other:
        for key, value in other.iteritems():
            _set_string(keyNameRoot + '\\' + key, value)

    if progID:
        # set the progID as the most specific that was given to us
        if verProgID:
            _set_string(keyNameRoot + '\\ProgID', verProgID)
        else:
            _set_string(keyNameRoot + '\\ProgID', progID)

        # Set up the root entries - version independent.
        if desc:
            _set_string(progID, desc)
        _set_string(progID + '\\CLSID', str(clsid))

        # Set up the root entries - version dependent.
        if verProgID:
            # point from independent to the current version
            _set_string(progID + '\\CurVer', verProgID)

            # point to the version-independent one
            _set_string(keyNameRoot + '\\VersionIndependentProgID', progID)

            # set up the versioned progID
            if desc:
                _set_string(verProgID, desc)
            _set_string(verProgID + '\\CLSID', str(clsid))
Exemplo n.º 29
0
 def _dllLocation(self):
     """
 @return  unicode
 @throw  WindowsError, AttributeError
 """
     return win32api.GetModuleFileName(self.dll._handle)