Esempio n. 1
0
    def set_windows_path(self, cocos_consle_root):
        import _winreg
        try:
            env = None
            path = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                'Environment',
                                0,
                                _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            path = _winreg.QueryValueEx(env, 'Path')[0]
            path = path + ';' + cocos_consle_root
            path.replace('/', '\\')
            _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
            _winreg.FlushKey(env)
            _winreg.CloseKey(env)

        except Exception:
            if not path:
                path = cocos_consle_root.replace('/', '\\')
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
            else:
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
            if env:
                _winreg.CloseKey(env)
            return False
        return True
Esempio n. 2
0
def extend(pypath):
    '''
    extend(pypath) adds pypath to the PATH env. variable as defined in the 
    registry, and then notifies applications (e.g. the desktop) of this change.
    Already opened DOS-Command prompt are not updated. Newly opened will have the
    new path (inherited from the updated windows explorer desktop)
    '''
    hKey = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE, 
               r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 
               0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE)
    
    value, typ = _winreg.QueryValueEx (hKey, "PATH")
    vals = value.split(';')
    assert isinstance(vals, list)
    if len(sys.argv) > 1 and sys.argv[1] == 'remove':
        try:
            vals.remove(pypath)
        except ValueError:
            print 'path element', pypath, 'not found'
            return
        print 'removing from PATH:', pypath
    else:
        if pypath in vals:
            print 'path element', pypath, 'already in PATH'
            return
        vals.append(pypath)
        print 'adding to PATH:', pypath
    _winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
    _winreg.FlushKey(hKey)
    # notify other programs
    SendMessage = ctypes.windll.user32.SendMessageW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
Esempio n. 3
0
def addAppLocationRegistryKey(software, location):
    connection = registry.ConnectRegistry(None, registry.HKEY_CURRENT_USER)
    key = registry.OpenKey(connection, r'Software\%s' % software, 0,
                           registry.KEY_WRITE)
    registry.SetValueEx(key, 'ExePath', 0, registry.REG_SZ, location)
    registry.FlushKey(key)
    key.Close()
Esempio n. 4
0
    def flush(self):
        """k.flush() -> None
		
		Ensures that this key is written to disk. Calls _winreg.FlushKey(). See
		<http://msdn.microsoft.com/library/en-us/sysinfo/base/regflushkey.asp>"""
        # Thanks to Shane Geiger for finding this bug.
        _winreg.FlushKey(self._handle)
Esempio n. 5
0
    def remove_dir_from_win_path(self, remove_dir):
        import _winreg
        try:
            env = None
            path = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, 'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            path = _winreg.QueryValueEx(env, 'Path')[0]

            path_lower = path.lower()
            remove_dir = remove_dir.replace('/', '\\')
            remove_dir_lower = remove_dir.lower()
            start_pos = path_lower.find(remove_dir_lower)
            if (start_pos >= 0):
                length = len(remove_dir_lower)
                need_remove = path[start_pos:(start_pos + length)]
                path = path.replace(need_remove, '')
                path = path.replace(';;', ';')
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
            _winreg.CloseKey(env)

            print('  ->Remove directory \"%s\" from PATH!\n' % remove_dir)
        except Exception:
            print('  ->Remove directory \"%s\" from PATH failed!\n' %
                  remove_dir)
Esempio n. 6
0
def writeregistrycommport(commport):
    reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    comkey = _winreg.OpenKey(
        reg,
        r"SOFTWARE\Wow6432Node\ASCOM\Telescope Drivers\ASCOM.Celestron.Telescope",
        0, _winreg.KEY_WRITE)
    _winreg.SetValueEx(comkey, 'CommPort', 0, _winreg.REG_SZ, telescopecom)
    _winreg.FlushKey(comkey)
    _winreg.CloseKey(comkey)
Esempio n. 7
0
def getregistrycommportvalue():
    reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    comkey = _winreg.OpenKey(
        reg,
        r"SOFTWARE\Wow6432Node\ASCOM\Telescope Drivers\ASCOM.Celestron.Telescope",
        0, _winreg.KEY_ALL_ACCESS)
    tmp = _winreg.QueryValueEx(comkey, 'CommPort')
    print tmp[0]
    _winreg.FlushKey(comkey)
    _winreg.CloseKey(comkey)
Esempio n. 8
0
    def announce(self):
        """Attempt to update the environment for running applications.

        @note: Requires PyWin32 (Unlike the rest of this class)
        @todo: Confirm this actually does something
        """
        winreg.FlushKey(self.env)  # TODO: Is this necessary?

        import win32api
        win32api.SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, None,
                             'Environment')
Esempio n. 9
0
    def SaveData(self, raw_data):
        logging.info("Writing back configuration to key %s", self.filename)

        # Ensure intermediate directories exist.
        try:
            for key, value in iteritems(raw_data):
                _winreg.SetValueEx(self.root_key, key, 0, _winreg.REG_SZ,
                                   utils.SmartStr(value))

        finally:
            # Make sure changes hit the disk.
            _winreg.FlushKey(self.root_key)
Esempio n. 10
0
    def set_windows_path(self, add_dir):
        ret = False
        import _winreg
        try:
            env = None
            path = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                    'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            path = _winreg.QueryValueEx(env, 'Path')[0]

            # add variable if can't find it in PATH
            path_lower = path.lower()
            add_dir_lower = add_dir.lower()
            if (path_lower.find(add_dir_lower) == -1):
                path = add_dir + ';' + path
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)

            _winreg.CloseKey(env)
            ret = True
        except Exception:
            if not path:
                path = add_dir
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
                ret = True
            else:
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
                ret = False

            if env:
                _winreg.CloseKey(env)

        if ret:
            print("  ->Add directory \"%s\" into PATH succeed!\n" % add_dir)
        else:
            print("  ->Add directory \"%s\" into PATH failed!\n" % add_dir)
Esempio n. 11
0
    def create_key(self):
        print("CREATE KEY")
        import datetime
        import pythoncom
        import _winreg

        with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.key_rep) as key:
            k = _winreg.CreateKey(key, self._reg_clsid_)
            _winreg.SetValueEx(k, "default", 0, _winreg.REG_DWORD, 1)
            _winreg.SetValueEx(k, "Title", 0, _winreg.REG_SZ,
                               self._reg_progid_)
            _winreg.SetValueEx(k, "Description", 0, _winreg.REG_SZ,
                               self._reg_desc_)
            _winreg.FlushKey(key)
def get_reg_value(mode):
    hKey = open_path_var_key(mode)
    try:
        reg_value, _ = _winreg.QueryValueEx(hKey, "PATH")
    except WindowsError as e:
        if e.errno == 2:  # The system cannot find the file specified
            # Create the value if it does not exist
            reg_value = ""
            _winreg.SetValueEx(hKey, "PATH", 0, _winreg.REG_EXPAND_SZ,
                               reg_value)
            _winreg.FlushKey(hKey)

    hKey.Close()

    return reg_value
Esempio n. 13
0
 def set_variable(self, name, value):
     """Sets an environment variable"""
     import _winreg
     try:
         env = None
         env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, 'Environment',
                                 0,
                                 _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
         _winreg.SetValueEx(env, name, 0, _winreg.REG_SZ, value)
         _winreg.FlushKey(env)
         _winreg.CloseKey(env)
     except Exception:
         if env:
             _winreg.CloseKey(env)
         raise Exception("failed to set '%s' environment variable" % name)
def set_path_var(mode, paths):
    reg_value = ";".join(paths)
    hKey = open_path_var_key(mode)
    _winreg.SetValueEx(hKey, "PATH", 0, _winreg.REG_EXPAND_SZ, reg_value)
    _winreg.FlushKey(hKey)
    hKey.Close()

    # Notify system of PATH change. Use SendMessageTimeout instead of
    # SendMessage because with Python 3 it hangs awaiting for response
    # that never comes
    SendMessageTimeout = ctypes.windll.user32.SendMessageTimeoutW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SMTO_ABORTIFHUNG = 0x2
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment',
                       SMTO_ABORTIFHUNG, 500)
Esempio n. 15
0
 def disableZoomIniE(self):
     regKey = wr.OpenKey(wr.HKEY_CURRENT_USER,
                         "SOFTWARE\\Microsoft\\Internet Explorer\\Zoom")
     try:
         i = 0
         while 1:
             name, value, type = wr.EnumValue(regKey, i)
             if name == "ZoomFactor":
                 print "%s  :   %s" % (name, value)
                 wr.SetValue(regKey, name, wr.REG_SZ, "100000")
                 wr.FlushKey(regKey)
                 wr.CloseKey(regKey)
                 print "%s  :   %s" % (name, value)
             i += 1
     except WindowsError:
         print
     wr.CloseKey(regKey)
Esempio n. 16
0
	def SetEnv(self, key, value):
		ret = True
		if self.platform == self.platforms.windows:
			import _winreg
			try:
				env = None
				env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
										"Environment", 0,
										_winreg.KEY_SET_VALUE|_winreg.KEY_READ)
				_winreg.SetValueEx(env, key, 0, _winreg.REG_SZ, value)
				_winreg.FlushKey(env)
			except Exception: ret = False
			finally:
				if env is not None: _winreg.CloseKey(env)
		elif (self.platform == self.platforms.linux
			or self.platform == self.platforms.mac):
			if self.file is not None:
				if self.GetEnv(key) is None:
					try:
						file = None
						file = open(self.file, "a")
						file.write("export %s=%s\n"%(key,value))
					except Exception: ret = False
					finally:
						if file is not None: file.close()
				else:
					try:
						fileR = None
						fileR = open(self.file, "r")
						fileW = None
						fileW = open(self.file, "w")
						lines = fileR.readlines()
						import re
						self.patten = re.compile(r"^export[ \t]+%s=(.+)"%key)
						for i in range(len(lines)):
							if self.patten.match(lines[i].lstrip(" \t")) is not None:
								lines[i] = "export %s=%s\n"%(key,value)
								break
						fileW.writelines(lines)
					except Exception: ret = False
					finally:
						if fileR is not None: fileR.close()
						if fileW is not None: fileW.close()
		else: ret = False
		return ret
Esempio n. 17
0
 def win_setup_ssh(self):
     "Makes sure windows users can use their SSH configs"
     if not 'HOME' in os.environ:
         print "You do not seem to have the HOME environment variable required by git ssh."
         ans = raw_input("Create it now? [y] ")
         if ans in (None, '', 'y', 'yes'):
             try:
                 import _winreg
                 key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                         'Environment')
                 _winreg.SetValue(
                     key, "HOME", _winreg.REG_SZ,
                     os.environ.get('USERPROFILE', None)
                     or os.path.expanduser('~'))
                 _winreg.FlushKey(key)
             except EnvironmentError:
                 print "Permission Denied. Please manually set \%HOME\% to %s" % os.path.expanduser(
                     '~')
Esempio n. 18
0
    def _set_environment_variable_win32(self, key, value):
        ret = False
        import _winreg
        try:
            env = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, 'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            _winreg.SetValueEx(env, key, 0, _winreg.REG_SZ, value)
            _winreg.FlushKey(env)
            _winreg.CloseKey(env)
            ret = True
        except Exception:
            if env:
                _winreg.CloseKey(env)
            ret = False

        return ret
Esempio n. 19
0
    def set(self, value_name, value_type, value):
        """Write and flush a value to a registry key.

        Args:
            value_name: A string that is the value name to fetch the value for
                        in the given key.
            value_type: The type of the value to write. Can be obtained from
                        WinReg.read or _winreg.KEY_*
            value: The value to be written
        """
        try:
            _winreg.SetValueEx(self.key_handle, value_name,
                               0, value_type, value)
            _winreg.FlushKey(self.key_handle)
        except WindowsError as e:
            err = unicode(str(e), errors='replace')
            self.log.error('Failed to set registry value: %s, because: %s',
                           self, err)
            raise e
Esempio n. 20
0
    def _set_environment_variable_win32(self, key, value):

        import _winreg
        try:
            env = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                'Environment',
                                0,
                                _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            _winreg.SetValueEx(env, key, 0, _winreg.REG_SZ, value)
            _winreg.FlushKey(env)
            _winreg.CloseKey(env)

        except Exception:
            if env:
                _winreg.CloseKey(env)
            print 'Warning: Could not add "%s" into registry' % key
            return False
        return True
Esempio n. 21
0
    def set_env_win(key, val):
        ret = False
        import _winreg
        try:
            env = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                    'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            _winreg.SetValueEx(env, key, 0, _winreg.REG_SZ, val)
            _winreg.FlushKey(env)
            _winreg.CloseKey(env)
            ret = True
        except Exception:
            if env:
                _winreg.CloseKey(env)
            ret = False

        if ret:
            print('\nPlease restart the terminal or restart computer to make added system variables take effect\n')

        return ret
Esempio n. 22
0
def main():
    import ctypes
    import getopt
    import re
    import _winreg

    import locale
    user_encoding = locale.getpreferredencoding() or 'ascii'

    import ctypes

    hkey_str = {
        _winreg.HKEY_LOCAL_MACHINE: 'HKEY_LOCAL_MACHINE',
        _winreg.HKEY_CURRENT_USER: '******',
        _winreg.HKEY_CLASSES_ROOT: 'HKEY_CLASSES_ROOT',
    }

    dry_run = False
    silent = False
    start_brz = False
    add_path = False
    delete_path = False
    add_shell_menu = False
    delete_shell_menu = False
    check_mfc71 = False

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hvnq", [
            "help",
            "version",
            "dry-run",
            "silent",
            "start-brz",
            "add-path",
            "delete-path",
            "add-shell-menu",
            "delete-shell-menu",
            "check-mfc71",
        ])

        for o, a in opts:
            if o in ("-h", "--help"):
                print(USAGE)
                return OK
            elif o in ("-v", "--version"):
                print(VERSION_FORMAT % (USAGE.splitlines()[0], VERSION))
                return OK

            elif o in ('-n', "--dry-run"):
                dry_run = True
            elif o in ('-q', '--silent'):
                silent = True

            elif o == "--start-brz":
                start_brz = True
            elif o == "--add-path":
                add_path = True
            elif o == "--delete-path":
                delete_path = True
            elif o == "--add-shell-menu":
                add_shell_menu = True
            elif o == "--delete-shell-menu":
                delete_shell_menu = True
            elif o == "--check-mfc71":
                check_mfc71 = True

    except getopt.GetoptError as msg:
        print(str(msg))
        print(USAGE)
        return ERROR

    # message box from Win32API
    MessageBoxA = ctypes.windll.user32.MessageBoxA
    MB_OK = 0
    MB_ICONERROR = 16
    MB_ICONEXCLAMATION = 48

    brz_dir = os.path.dirname(os.path.abspath(sys.argv[0]))

    if start_brz:
        fname = os.path.join(brz_dir, "start_brz.bat")
        if os.path.isfile(fname):
            with open(fname, "r") as f:
                content = f.readlines()
        else:
            content = ["brz.exe help\n"]

        for ix in xrange(len(content)):
            s = content[ix]
            if re.match(r'.*(?<!\\)brz\.exe([ "].*)?$', s.rstrip('\r\n'),
                        re.IGNORECASE):
                content[ix] = s.replace(
                    'brz.exe', '"%s"' % os.path.join(brz_dir, 'brz.exe'))
            elif s.find(r'C:\Program Files\Breezy') != -1:
                content[ix] = s.replace(r'C:\Program Files\Breezy', brz_dir)

        if dry_run:
            print("*** Write file: start_brz.bat")
            print("*** File content:")
            print(''.join(content))
        else:
            with open(fname, 'w') as f:
                f.write(''.join(content))

    if (add_path or delete_path) and winver == 'Windows NT':
        # find appropriate registry key:
        # 1. HKLM\System\CurrentControlSet\Control\SessionManager\Environment
        # 2. HKCU\Environment
        keys = (
            (_winreg.HKEY_LOCAL_MACHINE, (r'System\CurrentControlSet\Control'
                                          r'\Session Manager\Environment')),
            (_winreg.HKEY_CURRENT_USER, r'Environment'),
        )

        hkey = None
        for key, subkey in keys:
            try:
                hkey = _winreg.OpenKey(key, subkey, 0, _winreg.KEY_ALL_ACCESS)
                try:
                    path_u, type_ = _winreg.QueryValueEx(hkey, 'Path')
                except WindowsError:
                    if key != _winreg.HKEY_CURRENT_USER:
                        _winreg.CloseKey(hkey)
                        hkey = None
                        continue
                    else:
                        path_u = u''
                        type_ = _winreg.REG_SZ
            except EnvironmentError:
                continue
            break

        if hkey is None:
            print("Cannot find appropriate registry key for PATH")
        else:
            path_list = [i for i in path_u.split(os.pathsep) if i != '']
            f_change = False
            for ix, item in enumerate(path_list[:]):
                if item == brz_dir:
                    if delete_path:
                        del path_list[ix]
                        f_change = True
                    elif add_path:
                        print("*** brz already in PATH")
                    break
            else:
                if add_path and not delete_path:
                    path_list.append(brz_dir.decode(user_encoding))
                    f_change = True

            if f_change:
                path_u = os.pathsep.join(path_list)
                if dry_run:
                    print("*** Registry key %s\\%s" % (hkey_str[key], subkey))
                    print("*** Modify PATH variable. New value:")
                    print(path_u)
                else:
                    _winreg.SetValueEx(hkey, 'Path', 0, type_, path_u)
                    _winreg.FlushKey(hkey)

        if hkey is not None:
            _winreg.CloseKey(hkey)

    if (add_path or delete_path) and winver == 'Windows 98':
        # mutating autoexec.bat
        # adding or delete string:
        # SET PATH=%PATH%;C:\PROGRA~1\Breezy
        abat = 'C:\\autoexec.bat'
        abak = 'C:\\autoexec.bak'

        def backup_autoexec_bat(name, backupname, dry_run):
            # backup autoexec.bat
            if os.path.isfile(name):
                if not dry_run:
                    shutil.copyfile(name, backupname)
                else:
                    print('*** backup copy of autoexec.bat created')

        GetShortPathName = ctypes.windll.kernel32.GetShortPathNameA
        buf = ctypes.create_string_buffer(260)
        if GetShortPathName(brz_dir, buf, 260):
            brz_dir_8_3 = buf.value
        else:
            brz_dir_8_3 = brz_dir
        pattern = 'SET PATH=%PATH%;' + brz_dir_8_3

        # search pattern
        with open(abat, 'r') as f:
            lines = f.readlines()
        found = False
        for i in lines:
            if i.rstrip('\r\n') == pattern:
                found = True
                break

        if delete_path and found:
            backup_autoexec_bat(abat, abak, dry_run)
            if not dry_run:
                with open(abat, 'w') as f:
                    for i in lines:
                        if i.rstrip('\r\n') != pattern:
                            f.write(i)
            else:
                print('*** Remove line <%s> from autoexec.bat' % pattern)

        elif add_path and not found:
            backup_autoexec_bat(abat, abak, dry_run)
            if not dry_run:
                with open(abat, 'a') as f:
                    f.write(pattern)
                    f.write('\n')
            else:
                print('*** Add line <%s> to autoexec.bat' % pattern)

    if add_shell_menu and not delete_shell_menu:
        hkey = None
        try:
            hkey = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
                                     r'Folder\shell\brz')
        except EnvironmentError:
            if not silent:
                MessageBoxA(None,
                            'Unable to create registry key for context menu',
                            'EnvironmentError', MB_OK | MB_ICONERROR)

        if hkey is not None:
            _winreg.SetValue(hkey, '', _winreg.REG_SZ, 'Brz Here')
            hkey2 = _winreg.CreateKey(hkey, 'command')
            _winreg.SetValue(
                hkey2, '', _winreg.REG_SZ,
                '%s /K "%s"' % (os.environ.get('COMSPEC', '%COMSPEC%'),
                                os.path.join(brz_dir, 'start_brz.bat')))
            _winreg.CloseKey(hkey2)
            _winreg.CloseKey(hkey)

    if delete_shell_menu:
        try:
            _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
                              r'Folder\shell\brz\command')
        except EnvironmentError:
            pass

        try:
            _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, r'Folder\shell\brz')
        except EnvironmentError:
            pass

    if check_mfc71:
        try:
            ctypes.windll.LoadLibrary('mfc71.dll')
        except WindowsError:
            MessageBoxA(None,
                        ("Library MFC71.DLL is not found on your system.\n"
                         "This library needed for SFTP transport.\n"
                         "If you need to work via SFTP you should download\n"
                         "this library manually and put it to directory\n"
                         "where Brz installed.\n"
                         "For detailed instructions see:\n"
                         "http://wiki.breezy-vcs.org/OnPureWindows"),
                        "Warning", MB_OK | MB_ICONEXCLAMATION)

    return OK
Esempio n. 23
0
 def Sync(self):
     if not self._synced:
         _winreg.FlushKey(_GetServiceKey())
         self._synced = True
Esempio n. 24
0
    def disableProtectedMode(self, hostName=None):

        self.regRoot = wr.ConnectRegistry(hostName, wr.HKEY_CURRENT_USER)

        self.strKeyPath = wr.OpenKeyEx(
            wr.HKEY_CURRENT_USER,
            "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\1\\"
        )
        try:
            i = 0
            while 1:
                name, value, type = wr.EnumValue(self.strKeyPath, i)
                if name == "2500":
                    print "%s  :   %s" % (name, value)
                    wr.SetValue(self.strKeyPath, name, wr.REG_SZ, "1")
                    wr.FlushKey(self.strKeyPath)
                    wr.CloseKey(self.strKeyPath)
                    print "%s  :   %s" % (name, value)
                i += 1
        except WindowsError:
            print
        wr.CloseKey(self.strKeyPath)

        self.strKeyPath = wr.OpenKeyEx(
            wr.HKEY_CURRENT_USER,
            "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\2\\"
        )
        try:
            i = 0
            while 1:
                name, value, type = wr.EnumValue(self.strKeyPath, i)
                if name == "2500":
                    print "%s  :   %s" % (name, value)
                    wr.SetValue(self.strKeyPath, name, wr.REG_SZ, "3")
                    wr.FlushKey(self.strKeyPath)
                    wr.CloseKey(self.strKeyPath)
                    print "%s  :   %s" % (name, value)
                i += 1
        except WindowsError:
            print
        wr.CloseKey(self.strKeyPath)

        self.strKeyPath = wr.OpenKeyEx(
            wr.HKEY_CURRENT_USER,
            "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3\\"
        )
        try:
            i = 0
            while 1:
                name, value, type = wr.EnumValue(self.strKeyPath, i)
                if name == "2500":
                    print "%s  :   %s" % (name, value)
                    wr.SetValue(self.strKeyPath, name, wr.REG_SZ, "3")
                    wr.FlushKey(self.strKeyPath)
                    wr.CloseKey(self.strKeyPath)
                    print "%s  :   %s" % (name, value)
                i += 1
        except WindowsError:
            print
        wr.CloseKey(self.strKeyPath)

        self.strKeyPath = wr.OpenKeyEx(
            wr.HKEY_CURRENT_USER,
            "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\4\\"
        )
        try:
            i = 0
            while 1:
                name, value, type = wr.EnumValue(self.strKeyPath, i)
                if name == "2500":
                    print "%s  :   %s" % (name, value)
                    wr.SetValue(self.strKeyPath, name, wr.REG_SZ, "3")
                    wr.FlushKey(self.strKeyPath)
                    wr.CloseKey(self.strKeyPath)
                    print "%s  :   %s" % (name, value)
                i += 1
        except WindowsError:
            print
        wr.CloseKey(self.strKeyPath)
Esempio n. 25
0
 def SyncTransactionLog(self):
     if not NannyController.synced:
         _winreg.FlushKey(self._GetKey())
         NannyController.synced = True
Esempio n. 26
0
    def _simulate_sync(self, doc):
        simulation = self.integrationSettings

        # Integration settings
        doc.Lookup('tStart').Value = simulation.startTime
        doc.Lookup('tStop').Value = simulation.stopTime
        doc.Lookup('relTol').Value = simulation.errorToleranceRel
        if simulation.errorToleranceAbs is None:
            if not self.config['Plugins']['SimulationX'].has_key('absTol'):
                absTol = simulation.errorToleranceRel
            else:
                absTol = self.config['Plugins']['SimulationX']['absTol']
            doc.Lookup('absTol').Value = absTol
        else:
            doc.Lookup('absTol').Value = simulation.errorToleranceAbs

        ialg = self._availableIntegrationAlgorithms.index(
            simulation.algorithmName)
        if self._IntegrationAlgorithmHasFixedStepSize[ialg]:
            doc.Lookup('dtMin').Value = simulation.fixedStepSize
        else:
            if not self.config['Plugins']['SimulationX'].has_key('dtMin'):
                dtMin = '1e-010'
            else:
                dtMin = self.config['Plugins']['SimulationX']['dtMin']
            doc.Lookup('dtMin').Value = dtMin
        if simulation.gridPointsMode == 'NumberOf':
            if simulation.gridPoints > 1:
                dtProtMin = (simulation.stopTime - simulation.startTime) / (
                    simulation.gridPoints - 1)
                protKind = 0  # = 'BaseModel.ProtKind.EquidistantTimeSteps'
            else:
                dtProtMin = (simulation.stopTime - simulation.startTime) / 500
                protKind = 0  # = 'BaseModel.ProtKind.EquidistantTimeSteps'
        elif simulation.gridPointsMode == 'Width':
            dtProtMin = simulation.gridWidth
            protKind = 0  # = 'BaseModel.ProtKind.EquidistantTimeSteps'
        elif simulation.gridPointsMode == 'Integrator':
            dtProtMin = 'dtDetect'
            protKind = 3  # = 'BaseModel.ProtKind.MinTimeStepsPrePostEvents'
        doc.Lookup('dtProtMin').Value = dtProtMin
        doc.Lookup('protKind').Value = protKind
        try:
            doc.SolverByName = self._solverByName[simulation.algorithmName]
        except KeyError:
            pass

        for name, newValue in self.changedStartValue.iteritems():
            i = name.find('[')
            if i >= 0 and name.endswith(']'):
                value = doc.Parameters(name[0:i]).Value
                n = name[i:]
                n = re.sub('[\[\]]', '', n)
                if self._isNumeric(n):
                    n = int(n)
                    value = re.sub('[\{\}\[\] ]', '', value)
                    value = value.replace(';', ',')
                    valueList = value.split(',')
                    valueList[n - 1] = newValue
                    doc.Parameters(
                        name[0:i]).Value = '{' + ','.join(valueList) + '}'
            else:
                doc.Parameters(name).Value = newValue

        # Build variable tree if empty, e.g. if simulate is called by the Testing plugin
        if not bool(self.variableTree.variable):
            self._fillTree(doc, doc)
            treeWasEmpty = True
        else:
            treeWasEmpty = False

        # Log all parameters and variables
        paramName = list()
        paramUnit = list()
        paramValue = list()
        for name, item in self.variableTree.variable.iteritems():
            pChild = doc.Lookup(name)
            childIsASimVariable = pChild.IsA(simVariable)
            if childIsASimVariable and not pChild.GetProperty(simIsInput):
                # Result
                try:
                    pChild.Protocol = True
                except:
                    try:
                        pChild.Parent.Results(pChild.Name).Protocol = True
                    except:
                        pass
            elif ((pChild.IsA(simParameter) or pChild.IsA(simGeneralParameter))
                  and not childIsASimVariable) or (
                      pChild.GetProperty(simIsInput) and childIsASimVariable):
                # Parameter
                childRelIdent = re.sub(r'\[.*?\]', '', name)
                childUnit = pChild.Unit.encode(locale.getpreferredencoding())
                childValue = pChild.Value
                dim = pChild.Execute('GetDimension', [])[0]
                if dim == '':
                    # Scalar dimension
                    if not childRelIdent in paramName:
                        paramName.append(childRelIdent)
                        paramUnit.append(childUnit)
                        if childValue == '':
                            childValue = 0
                        paramValue.append(childValue)
                elif self._isNumeric(dim):
                    # Fixed vector dimension
                    dim = int(dim)
                    childValue = re.sub('[\{\}\[\] ]', '', childValue)
                    childValue = childValue.replace(';', ',')
                    childValueList = childValue.split(',')
                    if len(childValueList) == dim:
                        for i in range(1, dim + 1):
                            if self._isNumeric(childValueList[i - 1]):
                                childCompName = childRelIdent + '[' + str(
                                    i) + ']'
                                if not childCompName in paramName:
                                    paramName.append(childCompName)
                                    paramUnit.append(childUnit)
                                    childValue = childValueList[i - 1]
                                    if childValue == '':
                                        childValue = 0
                                    paramValue.append(childValue)

        # Start simulation
        doc.Reset()
        time.sleep(0.01)
        doc.Start()

        # Wait till simulation is finished
        while doc.SolutionState < simStopped:
            if self.simulationStopRequest:
                doc.Stop()
                self.simulationStopRequest = False
                raise (Plugins.Simulator.SimulatorBase.Stopping)
            time.sleep(0.1)

        # Integration is finished
        if doc.SolutionState == simStopped:
            # Save results in CSV file
            resultFileName = os.path.abspath(
                simulation.resultFileName).replace('\\', '/')
            ver = self.config['Plugins']['SimulationX']['version']
            canExportDisplayUnit = True
            if ver == 'Iti.Simx36':
                ver = '3.6'
            elif ver == 'Iti.Simx37':
                ver = '3.7'
            else:
                ver = '3.5'
                canExportDisplayUnit = False

            try:
                key = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    r'Software\ITI GmbH\SimulationX ' + ver + r'\DataFilter',
                    0, winreg.KEY_ALL_ACCESS)
            except WindowsError:
                key = winreg.CreateKeyEx(
                    winreg.HKEY_CURRENT_USER,
                    r'Software\ITI GmbH\SimulationX ' + ver + r'\DataFilter',
                    0, winreg.KEY_ALL_ACCESS)
            try:
                frt = winreg.QueryValueEx(key, 'Format')
            except WindowsError:
                frt = (u'%.15lg', winreg.REG_SZ)
            try:
                dec = winreg.QueryValueEx(key, 'Dec')
            except WindowsError:
                dec = (u'.', winreg.REG_SZ)
            try:
                sep = winreg.QueryValueEx(key, 'Separator')
            except WindowsError:
                sep = (u'\t', winreg.REG_SZ)
            try:
                adT = winreg.QueryValueEx(key, 'AddTableName')
            except WindowsError:
                adT = (0, winreg.REG_DWORD)
            try:
                adN = winreg.QueryValueEx(key, 'AddColumnNames')
            except WindowsError:
                adN = (1, winreg.REG_DWORD)
            try:
                adU = winreg.QueryValueEx(key, 'AddColumnUnits')
            except WindowsError:
                adU = (0, winreg.REG_DWORD)
            winreg.SetValueEx(key, 'Format', 0, winreg.REG_SZ, '%.17lg')
            winreg.SetValueEx(key, 'Dec', 0, winreg.REG_SZ, '.')
            winreg.SetValueEx(key, 'Separator', 0, winreg.REG_SZ, ';')
            winreg.SetValueEx(key, 'AddTableName', 0, winreg.REG_DWORD, 0)
            winreg.SetValueEx(key, 'AddColumnNames', 0, winreg.REG_DWORD, 1)
            winreg.SetValueEx(key, 'AddColumnUnits', 0, winreg.REG_DWORD, 1)
            winreg.FlushKey(key)
            if canExportDisplayUnit:
                doc.StoreAllResultsAsText(resultFileName,
                                          False)  # Export in displayUnit
            else:
                doc.StoreAllResultsAsText(resultFileName)  # Export in SI-Unit
            winreg.SetValueEx(key, 'Format', 0, winreg.REG_SZ, frt[0])
            winreg.SetValueEx(key, 'Dec', 0, winreg.REG_SZ, dec[0])
            winreg.SetValueEx(key, 'Separator', 0, winreg.REG_SZ, sep[0])
            winreg.SetValueEx(key, 'AddTableName', 0, winreg.REG_DWORD, adT[0])
            winreg.SetValueEx(key, 'AddColumnNames', 0, winreg.REG_DWORD,
                              adN[0])
            winreg.SetValueEx(key, 'AddColumnUnits', 0, winreg.REG_DWORD,
                              adU[0])
            winreg.CloseKey(key)

            # Save parameters in CSV file
            if len(paramName) > 0:
                with open(resultFileName + 'p', 'wb') as csvfile:
                    csvwriter = csv.writer(csvfile, delimiter=';')
                    csvwriter.writerow(paramName)
                    csvwriter.writerow(paramUnit)
                    csvwriter.writerow(paramValue)

            self.integrationStatistics.reachedTime = simulation.stopTime
            self.integrationStatistics.nGridPoints = len(
                doc.Lookup('t').ProtValues)
        elif doc.SolutionState == simFailed:
            print('SimulationX: Simulation error.')

        if treeWasEmpty:
            self.variableTree.variable.clear()
                        print "*** Bzr already in PATH"
                    break
            else:
                if add_path and not delete_path:
                    path_list.append(bzr_dir.decode(user_encoding))
                    f_change = True

            if f_change:
                path_u = os.pathsep.join(path_list)
                if dry_run:
                    print "*** Registry key %s\\%s" % (hkey_str[key], subkey)
                    print "*** Modify PATH variable. New value:"
                    print path_u
                else:
                    _winreg.SetValueEx(hkey, 'Path', 0, type_, path_u)
                    _winreg.FlushKey(hkey)

        if not hkey is None:
            _winreg.CloseKey(hkey)

    if (add_path or delete_path) and winver == 'Windows 98':
        # mutating autoexec.bat
        # adding or delete string:
        # SET PATH=%PATH%;C:\PROGRA~1\Bazaar
        abat = 'C:\\autoexec.bat'
        abak = 'C:\\autoexec.bak'

        def backup_autoexec_bat(name, backupname, dry_run):
            # backup autoexec.bat
            if os.path.isfile(name):
                if not dry_run:
Esempio n. 28
0
def close_keys(dkeys):
    for dkey in dkeys:
        wr.FlushKey(dkey)
        dkey.Close()
Esempio n. 29
0
'''
Copyright (c) 2014-2016 Ehsan Iran-Nejad
Python scripts for Autodesk Revit

This file is part of pyRevit repository at https://github.com/eirannejad/pyRevit

pyRevit is a free set of scripts for Autodesk Revit: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
'''

__window__.Close()
import _winreg as wr
k = wr.OpenKey(wr.HKEY_CURRENT_USER,r'Software\Bluebeam Software\Brewery\V45\Printer Driver',0,wr.KEY_WRITE)
wr.SetValueEx(k,r'PromptForFileName',0,wr.REG_SZ,'1')
#wr.QueryValueEx(k,r'PromptForFileName')
wr.FlushKey(k)
k.Close()
print('Done...Bluebeam Ask for Filename Dialog Enabled...')
Esempio n. 30
0
        epilog="Then restart service")
    parser.add_argument('host',
                        metavar='HOST',
                        help='New synergy server IP address')
    args = parser.parse_args()

    try:
        socket.inet_aton(args.host)
    except socket.error:
        sys.stderr.write('%s is not a valid host\n' % args.host)
        sys.exit(-1)

    hostregkey = _winreg.OpenKey(
        _winreg.HKEY_CURRENT_USER, 'Software\\Synergy\\Synergy', 0,
        _winreg.KEY_READ | _winreg.KEY_QUERY_VALUE | _winreg.KEY_SET_VALUE)
    oldhost, type = _winreg.QueryValueEx(hostregkey, 'serverHostname')
    print 'Change synergy server from %s to %s' % (oldhost, args.host)
    _winreg.SetValueEx(hostregkey, 'serverHostname', 0, type, args.host)
    _winreg.FlushKey(hostregkey)

    cmdregkey = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Synergy', 0,
        _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ | _winreg.KEY_QUERY_VALUE
        | _winreg.KEY_SET_VALUE)
    oldcmd, type = _winreg.QueryValueEx(cmdregkey, 'Command')
    _winreg.SetValueEx(cmdregkey, 'Command', 0, type,
                       oldcmd.replace(oldhost, args.host))
    _winreg.FlushKey(cmdregkey)

    win32serviceutil.RestartService('Synergy')