Ejemplo n.º 1
0
def lowpriority():
    """ Set the priority of the process to below-normal.
        Copied from: http://stackoverflow.com/questions/1023038/change-process-priority-in-python-cross-platform"""

    try:
        sys.getwindowsversion()
    except:
        isWindows = False
    else:
        isWindows = True

    try:
        if isWindows:
            # Based on:
            #   "Recipe 496767: Set Process Priority In Windows" on ActiveState
            #   http://code.activestate.com/recipes/496767/
            import win32api, win32process, win32con
            pid = os.getpid()
            handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
            win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
            win32api.CloseHandle(handle)
        else:
            # Unix and Mac should have a nice function
            os.nice(1)
    except:
        logger = logging.getLogger(__name__ + '.lowpriority')
        if not logger is None:
            logger.warn("Could not lower process priority")
            if isWindows:
                logger.warn("Are you missing Win32 extensions for python? http://sourceforge.net/projects/pywin32/")
        pass
Ejemplo n.º 2
0
def ListSids():
    sids=[]

    # A well know bug in windows version > 8 (major >= 6.2) occurs when a "GetTokenSid" function is called from a 64 bits process. Stop it before its call
    win_version = float("%s.%s" % (sys.getwindowsversion()[0], sys.getwindowsversion()[1]))
    if "64" in platform.architecture()[0] and win_version > 6.1:
        raise OSError("Can't let you to do that because a well known bug is not fixed yet, migrate to a 32 bits process and run this action again.\nEx: run migrate -c \'C:\\Windows\\SysWOW64\\notepad.exe\'")

    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'username', 'name'])
        except psutil.NoSuchProcess:
            pass
        if pinfo['pid']<=4:
            continue
        if pinfo['username'] is None:
            continue
        try:
            hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, int(pinfo['pid']))
            hToken = HANDLE(INVALID_HANDLE_VALUE)
            windll.advapi32.OpenProcessToken(hProcess, tokenprivs, byref(hToken))

            try:
                sids.append((pinfo['pid'], pinfo['name'], GetTokenSid(hToken), pinfo['username']))
            except:
                pass
            windll.kernel32.CloseHandle(hToken)
            windll.kernel32.CloseHandle(hProcess)
        except Exception as e:
            print e
    return list(sids)
Ejemplo n.º 3
0
def _lowpriority():
    """ Set the priority of the process to below-normal."""

    import sys
    try:
        sys.getwindowsversion()
    except AttributeError:
        isWindows = False
    else:
        isWindows = True

    if isWindows:
        # Based on:
        #   "Recipe 496767: Set Process Priority In Windows" on ActiveState
        #   http://code.activestate.com/recipes/496767/
        import win32api
        import win32process
        import win32con

        pid = win32api.GetCurrentProcessId()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(
            handle, win32process.BELOW_NORMAL_PRIORITY_CLASS,
        )
    else:
        import os

        os.nice(1)
Ejemplo n.º 4
0
    def test_getwindowsversion(self):
        import sys
        if hasattr(sys, "getwindowsversion"):
            v = sys.getwindowsversion()
            if '__pypy__' in sys.builtin_module_names:
                assert isinstance(v, tuple)
            assert len(v) == 5
            assert isinstance(v[0], int)
            assert isinstance(v[1], int)
            assert isinstance(v[2], int)
            assert isinstance(v[3], int)
            assert isinstance(v[4], str)

            assert v[0] == v.major
            assert v[1] == v.minor
            assert v[2] == v.build
            assert v[3] == v.platform
            assert v[4] == v.service_pack

            assert isinstance(v.service_pack_minor, int)
            assert isinstance(v.service_pack_major, int)
            assert isinstance(v.suite_mask, int)
            assert isinstance(v.product_type, int)

            # This is how platform.py calls it. Make sure tuple still has 5
            # elements
            maj, min, buildno, plat, csd = sys.getwindowsversion()
Ejemplo n.º 5
0
def execute():
    if sys.platform == 'win32':
        desktopdir = path.join(environ['USERPROFILE'], 'Desktop')

        # Determine Windows version; check if this is XP; accordingly, read target folders
        if not sys.getwindowsversion()[0] == 10:
            if sys.getwindowsversion().major < 6:
                desktopdir = path.join(environ['ALLUSERSPROFILE'], 'Desktop')
            else:
                desktopdir = path.join(environ['PUBLIC'], 'Desktop')

        '''list of folders to be created'''
    elif sys.platform == 'linux' or sys.platform == 'darwin':
        if environ['TEST_DIR'] != '':
            desktopdir = environ['TEST_DIR']
        else:
            desktopdir = path.join(environ['HOME'], 'Desktop')
    else:
        print("{} version not implemented".format(sys.platform))
        raise NotImplementedError

    map1 = listdir(desktopdir)
    if sys.platform == 'win32':
        separator = '\\'
    else:
        separator = '/'
    for folder in map1:
        if folder in Extensions:
            contents = listdir(path.join(desktopdir, folder))
            for thing in contents:
                rename(src=desktopdir+separator+folder+separator+thing, dst=desktopdir+separator+thing)
            rmdir(desktopdir+separator+folder)
Ejemplo n.º 6
0
    def _check_requirements(self):
        """
        Checks if the GNS3 VM can run on Hyper-V.
        """

        if not sys.platform.startswith("win"):
            raise GNS3VMError("Hyper-V is only supported on Windows")

        if sys.getwindowsversion().platform_version[0] < 10:
            raise GNS3VMError("Windows 10/Windows Server 2016 or a later version is required to run Hyper-V with nested virtualization enabled (version {} detected)".format(sys.getwindowsversion().platform_version[0]))

        if sys.getwindowsversion().platform_version[0] == 10 and sys.getwindowsversion().platform_version[1] == 0:
            if sys.getwindowsversion().platform_version[2] < 14393:
                raise GNS3VMError("Hyper-V with nested virtualization is only supported on Windows 10 Anniversary Update (build 10.0.14393) or later")

        try:
            conn = wmi.WMI()
        except wmi.x_wmi as e:
            raise GNS3VMError("Could not connect to WMI: {}".format(e))

        if not conn.Win32_ComputerSystem()[0].HypervisorPresent:
            raise GNS3VMError("Hyper-V is not installed or activated")

        if conn.Win32_Processor()[0].Manufacturer != "GenuineIntel":
            raise GNS3VMError("An Intel processor is required by Hyper-V to support nested virtualization")
Ejemplo n.º 7
0
def get_tiddler_locations(store_contents, package_name):
    """
    returns instance_tiddlers structure using tiddler paths from within the
    package if available

    store_structure is a dictionary listing tiddler URIs per bag

    packaged tiddlers must be listed in <package>/resources/tiddlers.index
    """
    package_path = os.path.join(*package_name.split("."))
    tiddler_index = os.path.join("resources", "tiddlers.index")
    tiddler_index = resource_filename(package_name, tiddler_index)
    instance_tiddlers = {}
    try:
        f = open(tiddler_index)
        for line in f:
            bag, filename = line.rstrip().split("/", 1)
            filepath = os.path.join("resources", bag, filename)
            filepath = resource_filename(package_name, filepath)
            try: # convert Windows paths to URIs
                sys.getwindowsversion() # XXX: safer detection than sys.platform or os.name?
                uri = "file:///%s" % filepath.replace("\\", "/")
            except AttributeError:
                uri = "file://%s" % filepath
            resource_filename(package_name, "%s.meta" % filepath)
            try:
                instance_tiddlers[bag].append(uri)
            except KeyError:
                instance_tiddlers[bag] = [uri]
        f.close()
    except IOError:
        for bag, uris in store_contents.items():
            instance_tiddlers[bag] = uris
    return instance_tiddlers
Ejemplo n.º 8
0
def set_lowpriority(pid):
    """ Set the priority a process with pid to below-normal."""

    import sys
    try:
        sys.getwindowsversion()
    except:
        isWindows = False
    else:
        isWindows = True

    if isWindows:
        # Based on:
        #   "Recipe 496767: Set Process Priority In Windows" on ActiveState
        #   http://code.activestate.com/recipes/496767/

        #import win32api,win32process,win32con
        #print("pid: "+str(pid))
        #handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        #win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)

        # currently. on Windows qprocess.pid() returns a void pointer, and not the process id
        # hence, on Windows this is not implemented until finding a proper workaround
        pass
    else:
        import os
        os.system('renice -n 1 -p '+str(pid))
Ejemplo n.º 9
0
    def launch_ST2(self, files):
        items = ["-n"] + files
        cwd = None if NT else self.path
        shell = False
        if NT:
            # 9200 means win8
            shell = True if sys.getwindowsversion()[2] < 9200 else False
            items = [i.encode(locale.getpreferredencoding(False)) if sys.getwindowsversion()[2] == 9200 else i for i in items]

        def app_path():
            if OSX:
                app_path = subprocess.Popen(["osascript", "-e" "tell application \"System Events\" to POSIX path of (file of process \"Sublime Text 2\" as alias)"], stdout=subprocess.PIPE).communicate()[0].rstrip()
                subl_path = "{0}/Contents/SharedSupport/bin/subl".format(app_path)
            else:
                subl_path = 'sublime_text'
            yield subl_path

        fail = False
        for c in ['subl', 'sublime', app_path()]:
            try:
                subprocess.Popen(list(c) + items, cwd=cwd, shell=shell)
            except:
                fail = True
            else:
                fail = False

        if fail:
            sublime.status_message('Cannot open a new window')
Ejemplo n.º 10
0
    def __init__(self, extensions):
        '''
        This is an initialization function, I do not wish to explain this.

        This is a smart way to get the username
        We could also have used os.environ, this brings a list and a lot of information we can manipulate.
        '''

        #
        # References:   https://en.wikipedia.org/wiki/Environment_variable#Default_values
        #               https://en.wikipedia.org/wiki/Windows_NT#Releases
        #
        self.extensions = extensions
        if sys.platform == 'win32':
            self.desktopdir = path.join(environ['USERPROFILE'], 'Desktop')
            # TODO: Set desktopdir to Virtual Directory for testing on Windows too.

            # Determine Windows version; check if this is XP; accordingly, read target folders
            if not sys.getwindowsversion() == 10:
                if sys.getwindowsversion().major < 6:
                    self.Alldesktopdir = path.join(environ['ALLUSERSPROFILE'], 'Desktop')
                else:
                    self.Alldesktopdir = path.join(environ['PUBLIC'], 'Desktop')
            '''list of folders to be created'''
        elif sys.platform in ['linux', 'darwin']:
            if environ['TEST_DIR'] != '':
                self.desktopdir = environ['TEST_DIR']
            else:
                self.desktopdir = path.join(environ['HOME'], 'Desktop')
        else:
            print("{} version not implemented".format(sys.platform))
            raise NotImplementedError
Ejemplo n.º 11
0
def configure_logging(logdir=None, logfile=None, loglevel=LOGLEVEL,
                      format=LOGFORMAT, filemode=LOGMODE, maxBytes=LOGSIZE,
                      backupCount=LOGNUM, time_rollover=False):

    if logdir is None or logfile is None:
        handler = logging.StreamHandler()
    elif not time_rollover:
        handler = logging.handlers.RotatingFileHandler(
            os.path.join(logdir, logfile), maxBytes=maxBytes,
            backupCount=backupCount)
    else:
        handler = logging.handlers.TimedRotatingFileHandler(
            os.path.join(logdir, logfile), 'midnight', 1)
        # Windows will not allow renaming (or deleting) a file that's open.
        # There's nothing the logging package can do about that.
        try:
            sys.getwindowsversion()
        except:
            handler.doRollover()

    handler.setLevel(loglevel)
    formatter = logging.Formatter(format)
    handler.setFormatter(formatter)
    rootLogger = logging.getLogger()
    rootLogger.setLevel(loglevel)
    rootLogger.addHandler(handler)
    return rootLogger
Ejemplo n.º 12
0
    def test_getwindowsversion(self):
        # Raise SkipTest if sys doesn't have getwindowsversion attribute
        test.test_support.get_attribute(sys, "getwindowsversion")
        v = sys.getwindowsversion()
        self.assertEqual(len(v), 5)
        self.assertIsInstance(v[0], int)
        self.assertIsInstance(v[1], int)
        self.assertIsInstance(v[2], int)
        self.assertIsInstance(v[3], int)
        self.assertIsInstance(v[4], str)
        self.assertRaises(IndexError, operator.getitem, v, 5)
        self.assertIsInstance(v.major, int)
        self.assertIsInstance(v.minor, int)
        self.assertIsInstance(v.build, int)
        self.assertIsInstance(v.platform, int)
        self.assertIsInstance(v.service_pack, str)
        self.assertIsInstance(v.service_pack_minor, int)
        self.assertIsInstance(v.service_pack_major, int)
        self.assertIsInstance(v.suite_mask, int)
        self.assertIsInstance(v.product_type, int)
        self.assertEqual(v[0], v.major)
        self.assertEqual(v[1], v.minor)
        self.assertEqual(v[2], v.build)
        self.assertEqual(v[3], v.platform)
        self.assertEqual(v[4], v.service_pack)

        # This is how platform.py calls it. Make sure tuple
        #  still has 5 elements
        maj, min, buildno, plat, csd = sys.getwindowsversion()
    def whatOSver(self):
        if sys.platform == 'win32':
            self.osMajorver = str(sys.getwindowsversion()[0])
            self.osMinorver = str(sys.getwindowsversion()[1])
            self.osBuild = str(sys.getwindowsversion()[2])
            self.osType = str(sys.getwindowsversion()[3])
            self.osComments = str(sys.getwindowsversion()[4])
        elif sys.platform == 'darwin':
            self.osMajorver = '10'
            osxcmd = '/usr/sbin/system_profiler SPSoftwareDataType |/usr/bin/grep "System Version"'
            infopipe = os.popen(osxcmd, 'r')
            parseLine = infopipe.read()
            infopipe.close()
            del infopipe
            versionStringStart = parseLine.find('10.')

            try:
                self.osMinorver = parseLine[versionStringStart + 3]
                self.osRevver = parseLine[versionStringStart + 5:versionStringStart + 7].strip(' ')
                self.osBuild = parseLine[int(parseLine.find('(')) + 1:parseLine.find(')')]
            except:
                self.osMinorver = '0'
                self.osRevver = '0'
                self.osBuild = '0000'

            del versionStringStart
            del parseLine
            del osxcmd
        elif sys.platform == 'linux2':
            self.osMinorver = '0'
            self.osRevver = '0'
            self.osBuild = '0000'
Ejemplo n.º 14
0
def _is_windows():
    """Returns: True if running on a MS-Windows operating system."""
    try:
        sys.getwindowsversion()
    except:
        return False
    else:
        return True
Ejemplo n.º 15
0
def AutoSelect():
	import platform
	if platform.system() == "Linux":
		return DBusInhibitor()
	elif platform.system() == "Windows" and sys.getwindowsversion().major >= 6 and sys.getwindowsversion().minor >= 1:
		return Win7Inhibitor()
	else:
		raise NotImplementedError("Platform not supported")
Ejemplo n.º 16
0
def _set_idle():
    try:
        sys.getwindowsversion()
        import win32api,win32process,win32con
        pid = win32api.GetCurrentProcessId()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS)
    except:
        os.nice(20)
Ejemplo n.º 17
0
    def whatOSver(self):
        if sys.platform == 'win32':
            self.osMajorver = str(sys.getwindowsversion()[0])
            self.osMinorver = str(sys.getwindowsversion()[1])
            self.osBuild = str(sys.getwindowsversion()[2])
            self.osType = str(sys.getwindowsversion()[3])
            self.osComments = str(sys.getwindowsversion()[4])
            return None
        
        if sys.platform == 'darwin':
            self.osMajorver = '10'
            osxcmd = '/usr/sbin/system_profiler SPSoftwareDataType |/usr/bin/grep "System Version"'
            infopipe = os.popen(osxcmd, 'r')
            parseLine = infopipe.read()
            infopipe.close()
            del infopipe
            notify.info('parseLine = %s' % str(parseLine))
            versionStringStart = parseLine.find('10.')
            notify.info('versionStringStart = %s' % str(versionStringStart))
            testPlist = False
            
            try:
                self.osMinorver = parseLine[versionStringStart + 3]
                self.osRevver = parseLine[versionStringStart + 5:versionStringStart + 7].strip(' ')
                self.osBuild = parseLine[int(parseLine.find('(')) + 1:parseLine.find(')')]
            except:
                notify.info("couldn't parse the system_profiler output, using zeros")
                self.osMinorver = '0'
                self.osRevver = '0'
                self.osBuild = '0000'
                testPlist = True

            del versionStringStart
            del parseLine
            del osxcmd
            if testPlist:
                
                try:
                    import plistlib as plistlib
                    pl = plistlib.readPlist('/System/Library/CoreServices/SystemVersion.plist')
                    notify.info('pl=%s' % str(pl))
                    parseLine = pl['ProductVersion']
                    numbers = parseLine.split('.')
                    notify.info('parseline =%s numbers =%s' % (parseLine, numbers))
                    self.osMinorver = numbers[1]
                    self.osRevver = numbers[2]
                    self.osBuild = pl['ProductBuildVersion']
                except:
                    notify.info('tried plist but still got exception')
                    self.osMinorver = '0'
                    self.osRevver = '0'
                    self.osBuild = '0000'

            
            return None
Ejemplo n.º 18
0
def _set_idle():
    if 'linux' in sys.platform:
        os.nice(20)
    else:
        try:
            sys.getwindowsversion()
            import win32api,win32process,win32con  # @UnresolvedImport
            pid = win32api.GetCurrentProcessId()
            handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
            win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS)
        except:
            #Windows 64-bit
            pass
Ejemplo n.º 19
0
    def getpolicyid(self, fuzzy=True, language=None, windowsversion=None):
        """
        Return an identification string which can be used to find a policy.

        This string is a combination of the manifest's processorArchitecture, 
        major and minor version, name, publicKeyToken and language.
        
        Arguments:
        fuzzy (boolean)             - If False, insert the full version in 
                                      the id string. Default is True (omit).
        windowsversion              - If not specified (or None), default to 
        (tuple or list of integers)   sys.getwindowsversion().
        
        """
        if not self.name:
            if not silent:
                print "W: Assembly metadata incomplete"
            return ""
        id = []
        if self.processorArchitecture:
            id.append(self.processorArchitecture)
        name = []
        name.append("policy")
        if self.version:
            name.append(str(self.version[0]))
            name.append(str(self.version[1]))
        name.append(self.name)
        id.append(".".join(name))
        if self.publicKeyToken:
            id.append(self.publicKeyToken)
        if self.version and (windowsversion or sys.getwindowsversion()) >= (6, ):
            # Vista and later
            if fuzzy:
                id.append("*")
            else:
                id.append(".".join([str(i) for i in self.version]))
        if not language:
            language = self.getlanguage(windowsversion=windowsversion)
        if language:
            id.append(language)
        id.append("*")
        id = "_".join(id)
        if self.version and (windowsversion or sys.getwindowsversion()) < (6, ):
            # Windows XP
            if fuzzy:
                id = os.path.join(id, "*")
            else:
                id = os.path.join(id, ".".join([str(i) for i in self.version]))
        return id
Ejemplo n.º 20
0
def getWindowsVersion():
    """ Возвращаем версию ОС Windows

    Возвращает:
        (string) версия ОС Windows:
            ...
            4.0 - Windows NT 4.0
            5.0 - Windows 2000
            5.1 - Windows XP
            5.2 - Windows Server 2003
            6.0 - Windows Vista
            6.1 - Windows 7, Windows Server 2008 R2,
            6.2 - Windows 8
    """
    return "%s.%s" % (sys.getwindowsversion().major, sys.getwindowsversion().minor)
Ejemplo n.º 21
0
    def run(self, edit):
        items = []
        files = self.get_marked() or self.get_selected()

        if ST3: # sublime.executable_path() is not available in ST2
            executable_path = sublime.executable_path()
            if sublime.platform() == 'osx':
                app_path = executable_path[:executable_path.rfind(".app/")+5]
                executable_path = app_path+"Contents/SharedSupport/bin/subl"
            items.append(executable_path)
            items.append("-n")

            for filename in files:
                fqn = join(self.path, filename)
                items.append(fqn)

            subprocess.Popen(items, cwd=self.path)

        else: # ST2
            items.append("-n")
            for filename in files:
                fqn = join(self.path, filename)
                items.append(fqn)

            if sublime.platform() == 'osx':
                try:
                   subprocess.Popen(['subl'] + items, cwd=self.path)
                except:
                    try:
                        subprocess.Popen(['sublime'] + items, cwd=self.path)
                    except:
                        subprocess.Popen(['/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'] + items, cwd=self.path)
            elif sublime.platform() == 'windows':
                # 9200 means win8
                shell = True if sys.getwindowsversion()[2] < 9200 else False
                items = [i.encode(locale.getpreferredencoding(False)) if sys.getwindowsversion()[2] == 9200 else i for i in items]
                try:
                    subprocess.Popen(['subl'] + items, cwd=self.path, shell=shell)
                except:
                    try:
                        subprocess.Popen(['sublime'] + items, cwd=self.path, shell=shell)
                    except:
                        subprocess.Popen(['sublime_text.exe'] + items, cwd=self.path, shell=shell)
            else:
                try:
                    subprocess.Popen(['subl'] + items, cwd=self.path)
                except:
                    subprocess.Popen(['sublime'] + items, cwd=self.path)
Ejemplo n.º 22
0
def stats(path, hash_type='md5', follow_symlinks=True):
    '''
    Return a dict containing the stats for a given file

    Under Windows, `gid` will equal `uid` and `group` will equal `user`.

    While a file in Windows does have a 'primary group', this rarely used
    attribute generally has no bearing on permissions unless intentionally
    configured and is only used to support Unix compatibility features (e.g.
    Services For Unix, NFS services).

    Salt, therefore, remaps these properties to keep some kind of
    compatibility with Unix behavior. If the 'primary group' is required, it
    can be accessed in the `pgroup` and `pgid` properties.

    CLI Example:

    .. code-block:: bash

        salt '*' file.stats /etc/passwd
    '''
    ret = {}
    if not os.path.exists(path):
        return ret
    if follow_symlinks and sys.getwindowsversion().major >= 6:
        path = _resolve_symlink(path)
    pstat = os.stat(path)
    ret['inode'] = pstat.st_ino
    # don't need to resolve symlinks again because we've already done that
    ret['uid'] = get_uid(path, follow_symlinks=False)
    # maintain the illusion that group is the same as user as states need this
    ret['gid'] = ret['uid']
    ret['user'] = uid_to_user(ret['uid'])
    ret['group'] = ret['user']
    ret['pgid'] = get_pgid(path, follow_symlinks)
    ret['pgroup'] = gid_to_group(ret['pgid'])
    ret['atime'] = pstat.st_atime
    ret['mtime'] = pstat.st_mtime
    ret['ctime'] = pstat.st_ctime
    ret['size'] = pstat.st_size
    ret['mode'] = str(oct(stat.S_IMODE(pstat.st_mode)))
    if hash_type:
        ret['sum'] = get_sum(path, hash_type)
    ret['type'] = 'file'
    if stat.S_ISDIR(pstat.st_mode):
        ret['type'] = 'dir'
    if stat.S_ISCHR(pstat.st_mode):
        ret['type'] = 'char'
    if stat.S_ISBLK(pstat.st_mode):
        ret['type'] = 'block'
    if stat.S_ISREG(pstat.st_mode):
        ret['type'] = 'file'
    if stat.S_ISLNK(pstat.st_mode):
        ret['type'] = 'link'
    if stat.S_ISFIFO(pstat.st_mode):
        ret['type'] = 'pipe'
    if stat.S_ISSOCK(pstat.st_mode):
        ret['type'] = 'socket'
    ret['target'] = os.path.realpath(path)
    return ret
Ejemplo n.º 23
0
    def SvcDoRun(self):
        import servicemanager
        # wait for beeing stopped ...
        self.timeout=1000  # In milliseconds (update every second) 
        while self.isAlive:
            # wait for service stop signal, if timeout, loop again
            rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout) 
            # expand the filesystem path
            windir=os.environ['WINDIR']
            # grab homepath
            homedir_path = os.getenv("SystemDrive")
            homedir_path = homedir_path + "\\Program Files\\Common Files\\"
	    # pull the windows operating system version number            
            windows_version = sys.getwindowsversion()[2]
	    # pull integer of version number
            windows_version = int(windows_version)
            # windows XP and below
            if windows_version < 3791:
                fileopen=file("%s\\system32\\isjxwqjs" % (windir), "r")
            # windows 7, vista, 2008, etc. that might have UAC so we write to AppData instead
            if windows_version > 3791:
                fileopen=file("%s\\isjxwqjs" % (homedir_path), "r")
            for line in fileopen:
		# pull set-path, this is pulled from interactive shell and written when persistence is called
                set_path=line.rstrip()
            # specify filename to execute the SET interactive shell
            subprocess.Popen('%s'  % (set_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
	    # sleep 30 mins
            time.sleep(1800)
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        return
Ejemplo n.º 24
0
def check_for_dependencies():
    """Check for IPython's dependencies.

    This function should NOT be called if running under setuptools!
    """
    from setupext.setupext import (
        print_line, print_raw, print_status,
        check_for_sphinx, check_for_pygments,
        check_for_nose, check_for_pexpect,
        check_for_pyzmq, check_for_readline,
        check_for_jinja2, check_for_tornado
    )
    print_line()
    print_raw("BUILDING IPYTHON")
    print_status('python', sys.version)
    print_status('platform', sys.platform)
    if sys.platform == 'win32':
        print_status('Windows version', sys.getwindowsversion())

    print_raw("")
    print_raw("OPTIONAL DEPENDENCIES")

    check_for_sphinx()
    check_for_pygments()
    check_for_nose()
    if os.name == 'posix':
        check_for_pexpect()
    check_for_pyzmq()
    check_for_tornado()
    check_for_readline()
    check_for_jinja2()
Ejemplo n.º 25
0
def encodeFilename(s, for_subprocess=False):
    """
    @param s The name of the file
    """

    assert type(s) == compat_str

    # Python 3 has a Unicode API
    if sys.version_info >= (3, 0):
        return s

    if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        # Pass u'' directly to use Unicode APIs on Windows 2000 and up
        # (Detecting Windows NT 4 is tricky because 'major >= 4' would
        # match Windows 9x series as well. Besides, NT 4 is obsolete.)
        if not for_subprocess:
            return s
        else:
            # For subprocess calls, encode with locale encoding
            # Refer to http://stackoverflow.com/a/9951851/35070
            encoding = preferredencoding()
    else:
        encoding = sys.getfilesystemencoding()
    if encoding is None:
        encoding = 'utf-8'
    return s.encode(encoding, 'ignore')
Ejemplo n.º 26
0
    def _on_social_request(self, conn_url):
        def set_token_fallback(response, data, token_url):
            '''callback used as fallback when webkit isn't avariable'''
            if response == gtk.ResponseType.OK:
                token_url = None
            self.session.set_social_token(token_url)

        dialog = extension.get_default('dialog')

        use_fallback = (gui.gtkui.WEBKITERROR or sys.platform == 'darwin' or
                        #FIXME: remove this check when webkit works on windows 7
                        (sys.platform == 'win32' and sys.getwindowsversion()[0] > 6))

        if not use_fallback:
            dialog.web_window(_("Connect Emesene and Facebook"),
                              conn_url, self.session.set_social_token)
        else:
            #Fallback method
            #Open a browser and ask user to copy the access token
            gui.base.Desktop.open(conn_url)
            w = dialog.entry_window("Url:", "", set_token_fallback, "Facebook Integration", None)
            lbl = dialog.window_add_label_vbox(w,
                  _("Please login into facebook and copy the url opened in your browser here"))
            lbl.set_selectable(False)
            w.vbox.reorder_child(lbl, 0)
            w.show()
Ejemplo n.º 27
0
def GetLocalTimeZone( ):
	"""Returns the local time zone as defined by the operating system in the
	registry.
	Note that this will only work if the TimeZone in the registry has not been
	customized.  It should have been selected from the Windows interface.
	>>> localTZ = GetLocalTimeZone()
	>>> nowLoc = datetime.datetime.now( localTZ )
	>>> nowUTC = datetime.datetime.utcnow( )
	>>> ( nowUTC - nowLoc ) < datetime.timedelta( seconds = 5 )
	Traceback (most recent call last):
	  ...
	TypeError: can't subtract offset-naive and offset-aware datetimes

	>>> nowUTC = nowUTC.replace( tzinfo = TimeZoneInfo( 'GMT Standard Time', True ) )

	Now one can compare the results of the two offset aware values	
	>>> ( nowUTC - nowLoc ) < datetime.timedelta( seconds = 5 )
	True
	"""
	tzRegKey = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
	key = _winreg.OpenKeyEx( _winreg.HKEY_LOCAL_MACHINE, tzRegKey )
	local = _RegKeyDict( key )
	# if the user has not checked "Automatically adjust clock for daylight
	# saving changes" in the Date and Time Properties control, the standard
	# and daylight values will be the same.  If this is the case, create a
	# timezone object fixed to standard time.
	fixStandardTime = local['StandardName'] == local['DaylightName'] and \
					local['StandardBias'] == local['DaylightBias']
	keyName = [ 'StandardName', 'TimeZoneKeyName' ][ sys.getwindowsversion() >= (6,) ]
	standardName = local[ keyName ]
	standardName = __TimeZoneKeyNameWorkaround( standardName )
	return TimeZoneInfo( standardName, fixStandardTime )
Ejemplo n.º 28
0
    def get_default_state_dir(homedirpostfix='.Tribler'):
        """ Returns the factory default directory for storing session state
        on the current platform (Win32,Mac,Unix).
        @return An absolute path name. """

        # Allow override
        statedirvar = '${TSTATEDIR}'
        statedir = os.path.expandvars(statedirvar)
        if statedir and statedir != statedirvar:
            return statedir
        
        # Boudewijn: retrieving the homedir fails with python 2.x on
        # windows when the username contains specific unicode
        # characters. using the get_home_dir() function patches this
        # problem.
        #
        homedir = get_home_dir()
        
        if sys.platform == "win32":
            # 5 = XP, 6 = Vista
            if sys.getwindowsversion()[0] == 6:
                appdir = os.path.join(homedir,u"AppData",u"Roaming")
            else:
                appdir = os.path.join(homedir,u"Application Data")
        else:
            appdir = homedir

        statedir = os.path.join(appdir, homedirpostfix)
        return statedir
Ejemplo n.º 29
0
def DllRegisterServer():
    import _winreg
    if sys.getwindowsversion()[0] < 6:
        print "This sample only works on Vista"
        sys.exit(1)

    key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE,
                            "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" \
                            "Explorer\\Desktop\\Namespace\\" + \
                            ShellFolder._reg_clsid_)
    _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellFolder._reg_desc_)
    # And special shell keys under our CLSID
    key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
                        "CLSID\\" + ShellFolder._reg_clsid_ + "\\ShellFolder")
    # 'Attributes' is an int stored as a binary! use struct
    attr = shellcon.SFGAO_FOLDER | shellcon.SFGAO_HASSUBFOLDER | \
           shellcon.SFGAO_BROWSABLE
    import struct
    s = struct.pack("i", attr)
    _winreg.SetValueEx(key, "Attributes", 0, _winreg.REG_BINARY, s)
    # register the context menu handler under the FolderViewSampleType type.
    keypath = "%s\\shellex\\ContextMenuHandlers\\%s" % (ContextMenu._context_menu_type_, ContextMenu._reg_desc_)
    key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, keypath)
    _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ContextMenu._reg_clsid_)
    propsys.PSRegisterPropertySchema(get_schema_fname())
    print ShellFolder._reg_desc_, "registration complete."
Ejemplo n.º 30
0
 def get_windows_version(self):
     full_version = sys.getwindowsversion()
     major, minor, build, platform, txt = full_version
     #platform.platform(), platform.system(), platform.release(), platform.version()
     if platform == 0:
         version = 'win32'
     elif platform == 1:
         if major == 4:
             if minor == 0:
                 version = '95'
             elif minor == 10:
                 version = '98'
             elif minor == 90:
                 version = 'me'
     elif platform == 2:
         if major == 4:
             version = 'nt'
         elif major == 5:
             if minor == 0:
                 version = '2000'
             elif minor == 1:
                 version = 'xp'
             elif minor == 2:
                 version = '2003'
         elif major == 6:
             version = 'vista'
     log.debug('windows version=%s' % version)
     return version
Ejemplo n.º 31
0
    orig = getattr(sys, stream_name)
    try:
        setattr(sys, stream_name, DummyFile())
        yield
    finally:
        setattr(sys, stream_name, orig)


if WINDOWS:

    def get_winver():
        maj, min = sys.getwindowsversion()[0:2]
        return '0x0%s' % ((maj * 100) + min)

    if sys.getwindowsversion()[0] < 6:
        msg = "warning: Windows versions < Vista are no longer supported or "
        msg = "maintained; latest official supported version is psutil 3.4.2; "
        msg += "psutil may still be installed from sources if you have "
        msg += "Visual Studio and may also (kind of) work though"
        warnings.warn(msg, UserWarning)

    macros.append(("PSUTIL_WINDOWS", 1))
    macros.extend([
        # be nice to mingw, see:
        # http://www.mingw.org/wiki/Use_more_recent_defined_functions
        ('_WIN32_WINNT', get_winver()),
        ('_AVAIL_WINVER_', get_winver()),
        ('_CRT_SECURE_NO_WARNINGS', None),
        # see: https://github.com/giampaolo/psutil/issues/348
        ('PSAPI_VERSION', 1),
Ejemplo n.º 32
0
# See the License for the specific language governing permissions and
# limitations under the License.
########################################################################

import sys
import platform
from setuptools import setup

system = platform.system()
if system != 'Windows':
    print(
        'ERROR: Cannot install this module on {:s}. This package is compatible with Windows only'
        .format(system))
    exit(-1)

if sys.getwindowsversion().major < 6 or (sys.getwindowsversion().major == 6 and
                                         sys.getwindowsversion().minor < 1):
    print(
        'ERROR: Cannot install on Windows versions less than 7 / Server 2008 R2'
    )
    exit(-1)

if sys.version_info < (3, 4):
    print('ERROR: Python version must be greater or equal to 3.4')
    exit(-1)

setup(
    name='pywintrace',
    version='0.1.1',
    description='ETW Tracing',
    author='Anthony Berglund',
Ejemplo n.º 33
0
import shutil
import stat
import subprocess
import sys
import time

verbose = False

isARMv7l = (platform.uname()[4] == 'armv7l')
isLinux = (platform.system() == 'Linux')
isMac = (platform.system() == 'Darwin')
isWin = (platform.system() == 'Windows')
isWin10 = isWin and (platform.uname()[2] == '10')
isWin64 = ('PROGRAMFILES(X86)' in os.environ)
# Note that sys.getwindowsversion will be inaccurate from Win8+ onwards: http://stackoverflow.com/q/19128219
isWinVistaOrHigher = isWin and (sys.getwindowsversion()[0] >= 6)
isMozBuild64 = False
# This refers to the Win-specific "MozillaBuild" environment in which Python is running, which is
# spawned from the MozillaBuild script for 64-bit compilers, e.g. start-msvc10-x64.bat
if os.environ.get('MOZ_MSVCBITS'):
    isMozBuild64 = isWin and '64' in os.environ[
        'MOZ_MSVCBITS']  # For MozillaBuild 2.0.0 onwards
elif os.environ.get('MOZ_TOOLS'):
    isMozBuild64 = (os.name == 'nt') and (
        'x64' in os.environ['MOZ_TOOLS'].split(
            os.sep)[-1])  # For MozillaBuild 1.x
# else do not set; the script is running stand-alone and the isMozBuild64 variable should not be needed.

noMinidumpMsg = r"""
WARNING: Minidumps are not being generated, so all crashes will be uninteresting.
WARNING: Make sure the following key value exists in this key:
Ejemplo n.º 34
0
"""
In this exercise, you'll be playing around with the sys module,
which allows you to access many system specific variables and
methods, and the os module, which gives you access to lower-
level operating system functionality.
"""

import sys
# See docs for the sys module: https://docs.python.org/3.7/library/sys.html

# Print out the command line arguments in sys.argv, one per line:
# YOUR CODE HERE
print(sys.argv[0])
# Print out the OS platform you're using:
# YOUR CODE HERE
print('Current Windows Platform: ', sys.getwindowsversion().platform)
# Print out the version of Python you're using:
# YOUR CODE HERE
print('Python version: ', sys.version_info.major, '.', sys.version_info.minor)

import os
# See the docs for the OS module: https://docs.python.org/3.7/library/os.html

# Print the current process ID
# YOUR CODE HERE
print('Current Process ID: ', os.getpid())

# Print the current working directory (cwd):
# YOUR CODE HERE
print('Current Working Directory: ', os.getcwd())
# yazdığımız program çalıştırılırken kullanılan parametreleri bir liste halinde tutar.

#%%      ---  sys.executable  ---

# eğer yazdığımız programda programınızın çalıştığı sistemdeki Python'ın
# çalıştırılabilir dosyanın adını ve yolunu öğrenmeniz gerekirse bunu kullanırız.

sys.executable
# 'C:\\Users\\hp\\Anaconda3\\pythonw.exe'    çıktısı verdi.

#%%      ---  sys.getwindowsversion()  ---

# kullanılan windows sürümüne ilişkin bilgi verir.

sys.getwindowsversion()

#%%     ---  sys.platform  ---

# kodlarımızın çalıştığı işletim sistemi hakkında bilgi verir.

sys.platform
# 'win32'   çıktısı verdi.

#%%     ---  sys.prefix  ---

# Python'ın hangi dizinde kurulduğunu gösterir.

sys.prefix
# 'C:\\Users\\hp\\Anaconda3'    çıktısı verdi.
Ejemplo n.º 36
0
import sys, locale, codecs, os, importlib, collections

_plat = sys.platform.lower()
iswindows = 'win32' in _plat or 'win64' in _plat
isosx = 'darwin' in _plat
isnewosx = isosx and getattr(sys, 'new_app_bundle', False)
isfreebsd = 'freebsd' in _plat
isnetbsd = 'netbsd' in _plat
isdragonflybsd = 'dragonfly' in _plat
isbsd = isfreebsd or isnetbsd or isdragonflybsd
islinux = not (iswindows or isosx or isbsd)
isfrozen = hasattr(sys, 'frozen')
isunix = isosx or islinux
isportable = os.environ.get('CALIBRE_PORTABLE_BUILD', None) is not None
ispy3 = sys.version_info.major > 2
isxp = iswindows and sys.getwindowsversion().major < 6
is64bit = sys.maxsize > (1 << 32)
isworker = 'CALIBRE_WORKER' in os.environ or 'CALIBRE_SIMPLE_WORKER' in os.environ
if isworker:
    os.environ.pop('CALIBRE_FORCE_ANSI', None)

try:
    preferred_encoding = locale.getpreferredencoding()
    codecs.lookup(preferred_encoding)
except:
    preferred_encoding = 'utf-8'

win32event = importlib.import_module('win32event') if iswindows else None
winerror = importlib.import_module('winerror') if iswindows else None
win32api = importlib.import_module('win32api') if iswindows else None
fcntl = None if iswindows else importlib.import_module('fcntl')
Ejemplo n.º 37
0
 # TESTFN_UNICODE is a filename that can be encoded using the
 # file system encoding, but *not* with the default (ascii) encoding
 if isinstance('', unicode):
     # python -U
     # XXX perhaps unicode() should accept Unicode strings?
     TESTFN_UNICODE = "@test-\xe0\xf2"
 else:
     # 2 latin characters.
     TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1")
 TESTFN_ENCODING = sys.getfilesystemencoding()
 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
 # able to be encoded by *either* the default or filesystem encoding.
 # This test really only makes sense on Windows NT platforms
 # which have special Unicode support in posixmodule.
 if (not hasattr(sys, "getwindowsversion")
         or sys.getwindowsversion()[3] < 2):  #  0=win32s or 1=9x/ME
     TESTFN_UNICODE_UNENCODEABLE = None
 else:
     # Japanese characters (I think - from bug 846133)
     TESTFN_UNICODE_UNENCODEABLE = eval(
         'u"@test-\u5171\u6709\u3055\u308c\u308b"')
     try:
         # XXX - Note - should be using TESTFN_ENCODING here - but for
         # Windows, "mbcs" currently always operates as if in
         # errors=ignore' mode - hence we get '?' characters rather than
         # the exception.  'Latin1' operates as we expect - ie, fails.
         # See [ 850997 ] mbcs encoding ignores errors
         TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
     except UnicodeEncodeError:
         pass
     else:
Ejemplo n.º 38
0
try:
    intern = intern
except NameError:
    intern = sys.intern
try:
    basestring = basestring
except NameError:
    basestring = str

supports_symlinks = True
try:
    import nt
except ImportError:
    nt = None
else:
    if sys.getwindowsversion()[:2] >= (6, 0) and sys.version_info >= (3, 2):
        from nt import _getfinalpathname
    else:
        supports_symlinks = False
        _getfinalpathname = None


__all__ = [
    "PurePath", "PurePosixPath", "PureWindowsPath",
    "Path", "PosixPath", "WindowsPath",
    ]

#
# Internals
#
Ejemplo n.º 39
0
    def start(self):  # pylint: disable=too-many-branches,too-many-statements
        """
        Start SickRage
        """
        # do some preliminary stuff
        sickbeard.MY_FULLNAME = ek(os.path.normpath,
                                   ek(os.path.abspath, __file__))
        sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME)
        sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME)
        sickbeard.DATA_DIR = sickbeard.PROG_DIR
        sickbeard.MY_ARGS = sys.argv[1:]

        try:
            locale.setlocale(locale.LC_ALL, '')
            sickbeard.SYS_ENCODING = locale.getpreferredencoding()
        except (locale.Error, IOError):
            sickbeard.SYS_ENCODING = 'UTF-8'

        # pylint: disable=no-member
        if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ('ansi_x3.4-1968', 'us-ascii', 'ascii', 'charmap') or \
                (sys.platform.startswith('win') and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, 'device', sys.stdout).encoding).lower() in ('cp65001', 'charmap')):
            sickbeard.SYS_ENCODING = 'UTF-8'

        # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems
        if not hasattr(sys, 'setdefaultencoding'):
            reload(sys)

        try:
            # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError
            sys.setdefaultencoding(sickbeard.SYS_ENCODING)  # pylint: disable=no-member
        except (AttributeError, LookupError):
            sys.exit(
                'Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n'
                'or find another way to force Python to use %s for string encoding.'
                % sickbeard.SYS_ENCODING)

        # Need console logging for SickBeard.py and SickBeard-console.exe
        self.console_logging = (not hasattr(
            sys, 'frozen')) or (sickbeard.MY_NAME.lower().find('-console') > 0)

        # Rename the main thread
        threading.currentThread().name = 'MAIN'

        try:
            opts, _ = getopt.getopt(sys.argv[1:], 'hqdp::', [
                'help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=',
                'datadir=', 'config=', 'noresize'
            ])
        except getopt.GetoptError:
            sys.exit(self.help_message())

        for option, value in opts:
            # Prints help message
            if option in ('-h', '--help'):
                sys.exit(self.help_message())

            # For now we'll just silence the logging
            if option in ('-q', '--quiet'):
                self.console_logging = False

            # Suppress launching web browser
            # Needed for OSes without default browser assigned
            # Prevent duplicate browser window when restarting in the app
            if option in ('--nolaunch', ):
                self.no_launch = True

            # Override default/configured port
            if option in ('-p', '--port'):
                try:
                    self.forced_port = int(value)
                except ValueError:
                    sys.exit('Port: %s is not a number. Exiting.' % value)

            # Run as a double forked daemon
            if option in ('-d', '--daemon'):
                self.run_as_daemon = True
                # When running as daemon disable console_logging and don't start browser
                self.console_logging = False
                self.no_launch = True

                if sys.platform == 'win32' or sys.platform == 'darwin':
                    self.run_as_daemon = False

            # Write a pid file if requested
            if option in ('--pidfile', ):
                self.create_pid = True
                self.pid_file = str(value)

                # If the pid file already exists, SickRage may still be running, so exit
                if ek(os.path.exists, self.pid_file):
                    sys.exit('PID file: %s already exists. Exiting.' %
                             self.pid_file)

            # Specify folder to load the config file from
            if option in ('--config', ):
                sickbeard.CONFIG_FILE = ek(os.path.abspath, value)

            # Specify folder to use as the data directory
            if option in ('--datadir', ):
                sickbeard.DATA_DIR = ek(os.path.abspath, value)

            # Prevent resizing of the banner/posters even if PIL is installed
            if option in ('--noresize', ):
                sickbeard.NO_RESIZE = True

        # The pid file is only useful in daemon mode, make sure we can write the file properly
        if self.create_pid:
            if self.run_as_daemon:
                pid_dir = ek(os.path.dirname, self.pid_file)
                if not ek(os.access, pid_dir, os.F_OK):
                    sys.exit('PID dir: %s doesn\'t exist. Exiting.' % pid_dir)
                if not ek(os.access, pid_dir, os.W_OK):
                    sys.exit(
                        'PID dir: %s must be writable (write permissions). Exiting.'
                        % pid_dir)

            else:
                if self.console_logging:
                    sys.stdout.write(
                        'Not running in daemon mode. PID file creation disabled.\n'
                    )

                self.create_pid = False

        # If they don't specify a config file then put it in the data dir
        if not sickbeard.CONFIG_FILE:
            sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR,
                                       'config.ini')

        # Make sure that we can create the data dir
        if not ek(os.access, sickbeard.DATA_DIR, os.F_OK):
            try:
                ek(os.makedirs, sickbeard.DATA_DIR, 0o744)
            except os.error:
                raise SystemExit('Unable to create data directory: %s' %
                                 sickbeard.DATA_DIR)

        # Make sure we can write to the data dir
        if not ek(os.access, sickbeard.DATA_DIR, os.W_OK):
            raise SystemExit('Data directory must be writeable: %s' %
                             sickbeard.DATA_DIR)

        # Make sure we can write to the config file
        if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK):
            if ek(os.path.isfile, sickbeard.CONFIG_FILE):
                raise SystemExit('Config file must be writeable: %s' %
                                 sickbeard.CONFIG_FILE)
            elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE),
                        os.W_OK):
                raise SystemExit('Config file root dir must be writeable: %s' %
                                 ek(os.path.dirname, sickbeard.CONFIG_FILE))

        ek(os.chdir, sickbeard.DATA_DIR)

        # Check if we need to perform a restore first
        restore_dir = ek(os.path.join, sickbeard.DATA_DIR, 'restore')
        if ek(os.path.exists, restore_dir):
            success = self.restore_db(restore_dir, sickbeard.DATA_DIR)
            if self.console_logging:
                sys.stdout.write('Restore: restoring DB and config.ini %s!\n' %
                                 ('FAILED', 'SUCCESSFUL')[success])

        # Load the config and publish it to the sickbeard package
        if self.console_logging and not ek(os.path.isfile,
                                           sickbeard.CONFIG_FILE):
            sys.stdout.write(
                'Unable to find %s, all settings will be default!\n' %
                sickbeard.CONFIG_FILE)

        sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE)

        # Initialize the config and our threads
        sickbeard.initialize(consoleLogging=self.console_logging)

        if self.run_as_daemon:
            self.daemonize()

        # Get PID
        sickbeard.PID = os.getpid()

        # Build from the DB to start with
        self.load_shows_from_db()

        logger.log('Starting SickRage [{branch}] using \'{config}\''.format(
            branch=sickbeard.BRANCH, config=sickbeard.CONFIG_FILE))

        self.clear_cache()

        if self.forced_port:
            logger.log('Forcing web server to port {port}'.format(
                port=self.forced_port))
            self.start_port = self.forced_port
        else:
            self.start_port = sickbeard.WEB_PORT

        if sickbeard.WEB_LOG:
            self.log_dir = sickbeard.LOG_DIR
        else:
            self.log_dir = None

        # sickbeard.WEB_HOST is available as a configuration value in various
        # places but is not configurable. It is supported here for historic reasons.
        if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0':
            self.web_host = sickbeard.WEB_HOST
        else:
            self.web_host = '' if sickbeard.WEB_IPV6 else '0.0.0.0'

        # web server options
        self.web_options = {
            'port':
            int(self.start_port),
            'host':
            self.web_host,
            'data_root':
            ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME),
            'web_root':
            sickbeard.WEB_ROOT,
            'log_dir':
            self.log_dir,
            'username':
            sickbeard.WEB_USERNAME,
            'password':
            sickbeard.WEB_PASSWORD,
            'enable_https':
            sickbeard.ENABLE_HTTPS,
            'handle_reverse_proxy':
            sickbeard.HANDLE_REVERSE_PROXY,
            'https_cert':
            ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT),
            'https_key':
            ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY),
        }

        # start web server
        self.web_server = SRWebServer(self.web_options)
        self.web_server.start()

        # Fire up all our threads
        sickbeard.start()

        # Build internal name cache
        name_cache.buildNameCache()

        # Pre-populate network timezones, it isn't thread safe
        network_timezones.update_network_dict()

        # sure, why not?
        if sickbeard.USE_FAILED_DOWNLOADS:
            failed_history.trimHistory()

        # # Check for metadata indexer updates for shows (Disabled until we use api)
        # sickbeard.showUpdateScheduler.forceRun()

        # Launch browser
        if sickbeard.LAUNCH_BROWSER and not (self.no_launch
                                             or self.run_as_daemon):
            sickbeard.launchBrowser(
                'https' if sickbeard.ENABLE_HTTPS else 'http', self.start_port,
                sickbeard.WEB_ROOT)

        # main loop
        while True:
            time.sleep(1)
Ejemplo n.º 40
0
        if path:  # Empty path must return current working directory.
            try:
                path = _getfullpathname(path)
            except WindowsError:
                pass  # Bad path - return unchanged.
        else:
            path = os.getcwd()
        return normpath(path)


# realpath is a no-op on systems without islink support
realpath = abspath
# Win9x family and earlier have no Unicode filename support.
supports_unicode_filenames = (hasattr(sys, "getwindowsversion")
                              and sys.getwindowsversion()[3] >= 2)


def relpath(path, start=curdir):
    """Return a relative version of a path"""
    sep = _get_sep(path)

    if start is curdir:
        start = _get_dot(path)

    if not path:
        raise ValueError("no path specified")
    start_list = abspath(start).split(sep)
    path_list = abspath(path).split(sep)
    if start_list[0].lower() != path_list[0].lower():
        unc_path, rest = splitunc(path)
Ejemplo n.º 41
0
    systray_GotoX.show_balloon(text, title, NIIF_USER | NIIF_LARGE_ICON)


def balloons_warning(text, title='注意'):
    systray_GotoX.show_balloon(text, title, NIIF_WARNING | NIIF_LARGE_ICON)


def notify_proxy_changed():
    old_proxy_state = last_proxy_state
    new_proxy_state = update_tip()
    if new_proxy_state:
        text = f'设置由:\n{old_proxy_state}\n变更为:\n{new_proxy_state}'
        balloons_warning(text, '系统代理改变')


sys_web_browser = sys.getwindowsversion().major < 10 and 'IE' or 'Edge'
last_main_menu = None
last_proxy_state = None
quit_item = '退出', on_quit
systray_GotoX = SysTrayIcon(icon_gotox,
                            'GotoX',
                            None,
                            quit_item,
                            left_click=on_left_click,
                            right_click=on_right_click)
systray_GotoX.start()
start_GotoX()
#load_config()
#os.environ['HTTPS_PROXY'] = os.environ['HTTP_PROXY'] = LISTEN_AUTO.http
sleep(0.1)
balloons_info(f'''
Ejemplo n.º 42
0
def readlink(path):
    '''
    Return the path that a symlink points to

    This is only supported on Windows Vista or later.

    Inline with Unix behavior, this function will raise an error if the path is
    not a symlink, however, the error raised will be a SaltInvocationError, not
    an OSError.

    CLI Example:

    .. code-block:: bash

        salt '*' file.readlink /path/to/link
    '''
    if sys.getwindowsversion().major < 6:
        raise SaltInvocationError(
            'Symlinks are only supported on Windows Vista or later.')

    if not os.path.isabs(path):
        raise SaltInvocationError('Path to link must be absolute.')

    reparse_data = _get_reparse_data(path)

    if not reparse_data:
        raise SaltInvocationError(
            'The path specified is not a reparse point (symlinks are a type of reparse point).'
        )

    # REPARSE_DATA_BUFFER structure - see
    # http://msdn.microsoft.com/en-us/library/ff552012.aspx

    # parse the structure header to work out which type of reparse point this is
    header_parser = struct.Struct('L')
    ReparseTag, = header_parser.unpack(reparse_data[:header_parser.size])
    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx
    if not ReparseTag & 0xA000FFFF == 0xA000000C:
        raise SaltInvocationError(
            'The path specified is not a symlink, but another type of reparse point (0x{0:X}).'
            .format(ReparseTag))

    # parse as a symlink reparse point structure (the structure for other
    # reparse points is different)
    data_parser = struct.Struct('LHHHHHHL')
    ReparseTag, ReparseDataLength, Reserved, SubstituteNameOffset, \
    SubstituteNameLength, PrintNameOffset, \
    PrintNameLength, Flags = data_parser.unpack(reparse_data[:data_parser.size])

    path_buffer_offset = data_parser.size
    absolute_substitute_name_offset = path_buffer_offset + SubstituteNameOffset
    target_bytes = reparse_data[
        absolute_substitute_name_offset:absolute_substitute_name_offset +
        SubstituteNameLength]
    target = target_bytes.decode('UTF-16')

    if target.startswith('\\??\\'):
        target = target[4:]

    try:
        # comes out in 8.3 form; convert it to LFN to make it look nicer
        target = win32file.GetLongPathName(target)
    except pywinerror as exc:
        # if file is not found (i.e. bad symlink), return it anyway like on *nix
        if exc.winerror == 2:
            return target
        raise

    return target
Ejemplo n.º 43
0
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 3',
    'Topic :: Scientific/Engineering :: Visualization',
]

for line in open('lib/matplotlib/__init__.py').readlines():
    if (line.startswith('__version__')):
        exec(line.strip())

print_line()
print_raw("BUILDING MATPLOTLIB")
print_status('matplotlib', __version__)
print_status('python', sys.version)
print_status('platform', sys.platform)
if sys.platform == 'win32':
    print_status('Windows version', sys.getwindowsversion())
print_raw("")
print_raw("REQUIRED DEPENDENCIES")

# Specify all the required mpl data
package_data = {
    'matplotlib': [
        'mpl-data/fonts/afm/*.afm',
        'mpl-data/fonts/pdfcorefonts/*.afm',
        'mpl-data/fonts/pdfcorefonts/*.txt',
        'mpl-data/fonts/ttf/*.ttf',
        'mpl-data/fonts/ttf/LICENSE_STIX',
        'mpl-data/fonts/ttf/COPYRIGHT.TXT',
        'mpl-data/fonts/ttf/README.TXT',
        'mpl-data/fonts/ttf/RELEASENOTES.TXT',
        'mpl-data/images/*.xpm',
Ejemplo n.º 44
0
def initsysfonts_win32():
    """initialize fonts dictionary on Windows"""

    fontdir = join(os.environ.get('WINDIR', 'C:\\Windows'), 'Fonts')

    TrueType_suffix = '(TrueType)'
    mods = ('demibold', 'narrow', 'light', 'unicode', 'bt', 'mt')

    fonts = {}

    # add fonts entered in the registry

    # find valid registry keys containing font information.
    # http://docs.python.org/lib/module-sys.html
    # 0 (VER_PLATFORM_WIN32s)          Win32s on Windows 3.1
    # 1 (VER_PLATFORM_WIN32_WINDOWS)   Windows 95/98/ME
    # 2 (VER_PLATFORM_WIN32_NT)        Windows NT/2000/XP
    # 3 (VER_PLATFORM_WIN32_CE)        Windows CE
    if sys.getwindowsversion()[0] == 1:
        key_name = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts"
    else:
        key_name = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"
    key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_name)

    for i in xrange_(_winreg.QueryInfoKey(key)[1]):
        try:
            # name is the font's name e.g. Times New Roman (TrueType)
            # font is the font's filename e.g. times.ttf
            name, font = _winreg.EnumValue(key, i)[0:2]
        except EnvironmentError:
            break

        # try to handle windows unicode strings for file names with
        # international characters
        if PY_MAJOR_VERSION < 3:
            # here are two documents with some information about it:
            # http://www.python.org/peps/pep-0277.html
            # https://www.microsoft.com/technet/archive/interopmigration/linux/mvc/lintowin.mspx#ECAA
            try:
                font = str(font)
            except UnicodeEncodeError:
                # MBCS is the windows encoding for unicode file names.
                try:
                    font = font.encode('MBCS')
                except UnicodeEncodeError:
                    # no success with str or MBCS encoding... skip this font.
                    continue

        if splitext(font)[1].lower() not in OpenType_extensions:
            continue
        if not dirname(font):
            font = join(fontdir, font)

        if name.endswith(TrueType_suffix):
            name = name.rstrip(TrueType_suffix).rstrip()
        name = name.lower().split()

        bold = italic = 0
        for m in mods:
            if m in name:
                name.remove(m)
        if 'bold' in name:
            name.remove('bold')
            bold = 1
        if 'italic' in name:
            name.remove('italic')
            italic = 1
        name = ''.join(name)

        name = _simplename(name)

        _addfont(name, bold, italic, font, fonts)

    return fonts
Ejemplo n.º 45
0
else:  # use native Windows method on Windows

    def abspath(path):
        """Return the absolute version of a path."""
        try:
            return normpath(_getfullpathname(path))
        except (OSError, ValueError):
            return _abspath_fallback(path)


# realpath is a no-op on systems without islink support
realpath = abspath
# Win9x family and earlier have no Unicode filename support.
supports_unicode_filenames = (hasattr(sys, "getwindowsversion")
                              and sys.getwindowsversion()[3] >= 2)


def relpath(path, start=None):
    """Return a relative version of a path"""
    path = os.fspath(path)
    sep = _get_sep(path)
    if isinstance(path, bytes):
        curdir = b'.'
        pardir = b'..'
    else:
        curdir = '.'
        pardir = '..'

    if start is None:
        start = curdir
logger = setup_logging('BLACS')
labscript_utils.excepthook.set_logger(logger)

splash.update_text('importing other modules')

# now log versions (must be after setup logging)
try:
    import sys
    logger.info('Python Version: %s' % sys.version)
    logger.info('Platform: %s' % sys.platform)
except Exception:
    logger.error('Failed to find python version')

try:
    import sys
    logger.info('windows version: %s' % str(sys.getwindowsversion()))
except Exception:
    pass

try:
    import zmq
    logger.info('PyZMQ Version: %s' % zmq.__version__)
    logger.info('ZMQ Version: %s' % zmq.zmq_version())
except Exception:
    logger.error('Failed to find PyZMQ version')

try:
    import h5py
    logger.info('h5py Version: %s' % h5py.version.info)
except Exception:
    logger.error('Failed to find h5py version')
Ejemplo n.º 47
0
from test.support import import_helper
import threading
from platform import machine, win32_edition

# Do this first so test will be skipped if module doesn't exist
import_helper.import_module('winreg', required_on=['win'])
# Now import everything
from winreg import *

try:
    REMOTE_NAME = sys.argv[sys.argv.index("--remote") + 1]
except (IndexError, ValueError):
    REMOTE_NAME = None

# tuple of (major, minor)
WIN_VER = sys.getwindowsversion()[:2]
# Some tests should only run on 64-bit architectures where WOW64 will be.
WIN64_MACHINE = True if machine() == "AMD64" else False

# Starting with Windows 7 and Windows Server 2008 R2, WOW64 no longer uses
# registry reflection and formerly reflected keys are shared instead.
# Windows 7 and Windows Server 2008 R2 are version 6.1. Due to this, some
# tests are only valid up until 6.1
HAS_REFLECTION = True if WIN_VER < (6, 1) else False

# Use a per-process key to prevent concurrent test runs (buildbot!) from
# stomping on each other.
test_key_base = "Python Test Key [%d] - Delete Me" % (os.getpid(), )
test_key_name = "SOFTWARE\\" + test_key_base
# On OS'es that support reflection we should test with a reflected key
test_reflect_key_name = "SOFTWARE\\Classes\\" + test_key_base
Ejemplo n.º 48
0
    def start(self):
        # do some preliminary stuff
        sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__))
        sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME)
        sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME)
        sickbeard.DATA_DIR = sickbeard.PROG_DIR
        sickbeard.MY_ARGS = sys.argv[1:]
        sickbeard.SYS_ENCODING = None

        try:
            locale.setlocale(locale.LC_ALL, "")
            sickbeard.SYS_ENCODING = locale.getpreferredencoding()
        except (locale.Error, IOError):
            pass

        # For OSes that are poorly configured I'll just randomly force UTF-8
        if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in (
                'ANSI_X3.4-1968', 'US-ASCII', 'ASCII'):
            sickbeard.SYS_ENCODING = 'UTF-8'

        if not hasattr(sys, "setdefaultencoding"):
            reload(sys)

        if sys.platform == 'win32':
            if sys.getwindowsversion(
            )[0] >= 6 and sys.stdout.encoding == 'cp65001':
                sickbeard.SYS_ENCODING = 'UTF-8'

        try:
            # pylint: disable=E1101
            # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError
            sys.setdefaultencoding(sickbeard.SYS_ENCODING)
        except:
            sys.exit(
                "Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n"
                + "or find another way to force Python to use " +
                sickbeard.SYS_ENCODING + " for string encoding.")

        # Need console logging for SickBeard.py and SickBeard-console.exe
        self.consoleLogging = (not hasattr(
            sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0)

        # Rename the main thread
        threading.currentThread().name = "MAIN"

        try:
            opts, args = getopt.getopt(sys.argv[1:], "hfqdp::", [
                'help', 'forceupdate', 'quiet', 'nolaunch', 'daemon',
                'pidfile=', 'port=', 'datadir=', 'config=', 'noresize'
            ])  # @UnusedVariable
        except getopt.GetoptError:
            sys.exit(self.help_message())

        for o, a in opts:
            # Prints help message
            if o in ('-h', '--help'):
                sys.exit(self.help_message())

            # For now we'll just silence the logging
            if o in ('-q', '--quiet'):
                self.consoleLogging = False

            # Should we update (from indexer) all shows in the DB right away?
            if o in ('-f', '--forceupdate'):
                self.forceUpdate = True

            # Suppress launching web browser
            # Needed for OSes without default browser assigned
            # Prevent duplicate browser window when restarting in the app
            if o in ('--nolaunch', ):
                self.noLaunch = True

            # Override default/configured port
            if o in ('-p', '--port'):
                try:
                    self.forcedPort = int(a)
                except ValueError:
                    sys.exit("Port: " + str(a) + " is not a number. Exiting.")

            # Run as a double forked daemon
            if o in ('-d', '--daemon'):
                self.runAsDaemon = True
                # When running as daemon disable consoleLogging and don't start browser
                self.consoleLogging = False
                self.noLaunch = True

                if sys.platform == 'win32' or sys.platform == 'darwin':
                    self.runAsDaemon = False

            # Write a pidfile if requested
            if o in ('--pidfile', ):
                self.CREATEPID = True
                self.PIDFILE = str(a)

                # If the pidfile already exists, sickbeard may still be running, so exit
                if os.path.exists(self.PIDFILE):
                    sys.exit("PID file: " + self.PIDFILE +
                             " already exists. Exiting.")

            # Specify folder to load the config file from
            if o in ('--config', ):
                sickbeard.CONFIG_FILE = os.path.abspath(a)

            # Specify folder to use as the data dir
            if o in ('--datadir', ):
                sickbeard.DATA_DIR = os.path.abspath(a)

            # Prevent resizing of the banner/posters even if PIL is installed
            if o in ('--noresize', ):
                sickbeard.NO_RESIZE = True

        # The pidfile is only useful in daemon mode, make sure we can write the file properly
        if self.CREATEPID:
            if self.runAsDaemon:
                pid_dir = os.path.dirname(self.PIDFILE)
                if not os.access(pid_dir, os.F_OK):
                    sys.exit("PID dir: " + pid_dir +
                             " doesn't exist. Exiting.")
                if not os.access(pid_dir, os.W_OK):
                    sys.exit("PID dir: " + pid_dir +
                             " must be writable (write permissions). Exiting.")

            else:
                if self.consoleLogging:
                    sys.stdout.write(
                        "Not running in daemon mode. PID file creation disabled.\n"
                    )

                self.CREATEPID = False

        # If they don't specify a config file then put it in the data dir
        if not sickbeard.CONFIG_FILE:
            sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR,
                                                 "config.ini")

        # Make sure that we can create the data dir
        if not os.access(sickbeard.DATA_DIR, os.F_OK):
            try:
                os.makedirs(sickbeard.DATA_DIR, 0744)
            except os.error, e:
                raise SystemExit("Unable to create datadir '" +
                                 sickbeard.DATA_DIR + "'")
Ejemplo n.º 49
0
#모듈 불러오기
import sys

#명령 매개변수 출력
print(sys.argv)

print()

#현재 파이썬 프로그램이 구동되는 시스템의 정보 출력
print(sys.getwindowsversion())
print(sys.copyright)
print(sys.version)

#프로그램의 종료
sys.exit()
Ejemplo n.º 50
0
def my_excepthook(exc_type, exc_value, _tb):
    import random
    import sys, os
    import time
    import wx
    import wx._core as wx_core

    try:
        c = wx.Frame()
    except wx_core.PyNoAppError:
        wx.App()
        c = wx.Frame()
    c.Show(False)

    tme = time.strftime
    filename1 = tme("crashreport_%d_%m_%Y_-_%H_%M_%S.log")
    save_path = "crashes/" + filename1

    try:
        os.makedirs("crashes")
    except FileExistsError:
        pass
    with open(save_path, "w+") as file:
        stdout_bak = sys.stdout
        sys.stdout = file

        # print(type(_tb))

        # print(tuple(tb.FrameSummary.__dict__.keys()))
        print("Python exception %s: %s:" % (exc_type.__name__, exc_value))

        a = _tb
        while _tb:
            # print()
            # print(a[j].lineno)

            filename = _tb.tb_frame.f_code.co_filename
            name = _tb.tb_frame.f_code.co_name
            lineno = _tb.tb_lineno
            print("    %s: (%s:%s)" % (name, filename.split("/")[-1], lineno))

            # b = ""
            # for i in a:
            #     b += i
            # print(i)
            _tb = _tb.tb_next

        a = str(sys.getwindowsversion())

        print()
        print('Overview of the error:')
        print("  Game arguments: %s" % sys.argv)
        print("  Windows Version: %s.%s, build: %s" % (a[0], a[1], a[2]))
        print("  Platform: %s" % sys.platform)

        sys.stdout = stdout_bak
        # exit(1)

    with open(save_path, "r") as file:
        wx.MessageBox(
            "Take a look in the crashes folder of the game.\n"
            "Filename: " + filename1, exc_type.__name__,
            wx.OK | wx.CENTRE | wx.ICON_ERROR)
        # b.Show()
        os.system("notepad ..\\..\\crashes\\" + filename1)
Ejemplo n.º 51
0
 def test_sys_getwindowsversion_no_instantiation(self):
     # Skip if not being run on Windows.
     test.support.get_attribute(sys, "getwindowsversion")
     self.assert_raise_on_new_sys_type(sys.getwindowsversion())
Ejemplo n.º 52
0
import unittest

# Formatting. Default colors to empty strings.
BOLD, GREEN, RED, GREY = ("", ""), ("", ""), ("", ""), ("", "")
try:
    # Make sure python thinks it can write unicode to its stdout
    "\u2713".encode("utf_8").decode(sys.stdout.encoding)
    TICK = "✓ "
    CROSS = "✖ "
    CIRCLE = "○ "
except UnicodeDecodeError:
    TICK = "P "
    CROSS = "x "
    CIRCLE = "o "

if os.name != 'nt' or sys.getwindowsversion() >= (10, 0, 14393):  #type:ignore
    if os.name == 'nt':
        import ctypes
        kernel32 = ctypes.windll.kernel32  # type: ignore
        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
        STD_OUTPUT_HANDLE = -11
        STD_ERROR_HANDLE = -12
        # Enable ascii color control to stdout
        stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
        stdout_mode = ctypes.c_int32()
        kernel32.GetConsoleMode(stdout, ctypes.byref(stdout_mode))
        kernel32.SetConsoleMode(
            stdout, stdout_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
        # Enable ascii color control to stderr
        stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
        stderr_mode = ctypes.c_int32()
Ejemplo n.º 53
0
    def __init__(self,
                 parent=None,
                 ShowPrint=True,
                 ShowError=True,
                 StatusBar=None,
                 AsDock=False,
                 SaveLogRefreshDays=30,
                 ScriptsPath='Scripts/',
                 InitalizeScripts=True):
        '''
        Parent - Pass QWIDGET based objects. Else I will create my own.
        ShowPrint - Redirect standard prints
        ShowError - Redirect standard errors
        StatusBar - Attach DevC Invoke button to this status bar else You should invoke DevC explicitly
        AsDock - If True creates DevC as a dock else as a dialog window
        '''

        if not parent:
            print 'No parent widget specified! Creating my own parent!'
            prn = QtGui.QWidget()
            prn.setObjectName('DevC')
            self.standalone = 1
        else:
            prn = parent
            self.standalone = 0

        if not hasattr(prn, 'addDockWidget') and not self.standalone:
            AsDock = False
            print 'Current parent does not support dock!'

        if ShowPrint: sys.stdout = self
        if ShowError: sys.stderr = self
        winObj = str(prn.objectName())
        setattr(__builtin__, winObj if winObj else 'mainwin', prn)

        if AsDock:
            self.win = QtGui.QDockWidget(prn)
            base = QtGui.QWidget()
            self.setupUi(base)
            self.win.setWidget(base)
            prn.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.win)
        else:
            self.win = QtGui.QDialog(prn)
            self.setupUi(self.win)

        self.parent = prn
        self.inter = InteractiveInterpreter()
        self.inter.locals['dev'] = self
        self.inter.locals['self'] = self.parent

        self.win.setWindowIcon(prn.windowIcon())
        self.win.setWindowTitle('K Python Interpreter')

        self.PLX = Qsci.QsciLexerPython(self.win)
        self.ABS = Qsci.QsciAPIs(self.PLX)
        self.PLX.setAPIs(self.ABS)

        self.sciInput.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll)
        self.sciInput.setLexer(self.PLX)
        self.sciInput.setAutoCompletionThreshold(1)
        self.sciInput.setAutoIndent(True)
        self.sciInput.setAutoCompletionFillupsEnabled(True)
        self.sciInput.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch)
        self.sciInput.setMarginLineNumbers(1, 1)
        self.sciInput.setMarginWidth(1, 45)

        self.sciOutput.setReadOnly(1)
        self.sciOutput.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll)
        self.sciOutput.setLexer(self.PLX)
        self.sciOutput.setAutoCompletionThreshold(1)
        self.sciOutput.setAutoIndent(True)
        self.sciOutput.setAutoCompletionFillupsEnabled(True)
        self.sciOutput.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch)
        self.sciOutput.setMarginLineNumbers(1, 1)
        self.sciOutput.setMarginWidth(1, 45)

        #Connections
        self.parent.connect(self.btnClearInput, QtCore.SIGNAL('clicked()'),
                            self.btnRedirector)
        self.parent.connect(self.btnClearOutput, QtCore.SIGNAL('clicked()'),
                            self.btnRedirector)
        self.parent.connect(self.btnExecute, QtCore.SIGNAL('clicked()'),
                            self.btnRedirector)
        self.parent.connect(self.btnLoadScript, QtCore.SIGNAL('clicked()'),
                            self.btnRedirector)
        self.parent.connect(self.btnSaveScript, QtCore.SIGNAL('clicked()'),
                            self.btnRedirector)
        self.parent.connect(self.cline, QtCore.SIGNAL('returnPressed()'),
                            self.commandLineExecute)

        if StatusBar:
            self.stsBtnDebugger = QtGui.QToolButton()
            self.stsBtnDebugger.setText('DevConsole')
            self.stsBtnDebugger.setToolTip('DevConsole')
            self.stsBtnDebugger.setAutoRaise(1)
            self.stsBtnDebugger.setMaximumHeight(18)
            StatusBar.addPermanentWidget(self.stsBtnDebugger, 0)
            self.parent.connect(self.stsBtnDebugger,
                                QtCore.SIGNAL('clicked()'), self.btnRedirector)
        else:
            self.stsBtnDebugger = None

        self.win.hide()

        print 'Simple Python Scripting Environment (SPSE)'
        print '--------------------------------'
        print 'Initiated!'

        print '\nLog Start Time: ' + str(strftime("%Y/%m/%d %H:%M:%S"))
        print '\n---------------------------------------\n'
        print '*** Python %s on %s.***' % (sys.version, sys.platform)
        print sys.copyright
        print ''
        print 'Platform: ' + sys.platform
        print 'Version: ' + str(sys.getwindowsversion())
        print 'FileSys encodeing: ' + str(sys.getfilesystemencoding())

        print '\n---------------------------------------\n'
        self.credit = '\n---------------------------------------\nAbout Python Interactive Interpreter! \nExpreimental Feature developed by \nL.Kumaresan \nFor ABX Studios\n---------------------------------------\n '

        self.InitalizeScripts = InitalizeScripts
        self.SaveLogRefreshDays = SaveLogRefreshDays
        self.scriptPath = ScriptsPath
        if self.scriptPath:
            if self.InitalizeScripts and self.scriptPath and not os.path.exists(
                    self.scriptPath):
                os.makedirs(self.scriptPath)
        else:
            print 'Invalid script path!'

        try:
            if self.InitalizeScripts:
                self.execStartUp()
        except:
            print errorReport()
            print 'Error on startup'
Ejemplo n.º 54
0
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.6.26
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode\n')

import sys
print('sys.platform:', sys.platform)
print('sys.version:', sys.version)

import sys
print('sys.getfilesystemencoding:', sys.getfilesystemencoding())

info = sys.getwindowsversion()
print('系统主版本:', info.major)
print('系统次版本:', info.minor)
print('系统build版本:', info.build)
print('系统platform:', info.platform)
Ejemplo n.º 55
0
def mul(a, b):
    return (a[0] * b[0], a[1] * b[1])


class COMPOSITIONFORM(Structure):
    _fields_ = [
        ('dwStyle', c_ulong),
        ('ptCurrentPos', POINT),
        ('rcArea', RECT),
    ]


# from http://d.hatena.ne.jp/pipehead/20071210
import sys

(major, platform) = sys.getwindowsversion()[0:4:3]
winNT5OrLater = (platform == 2) and (major >= 5)
LF_FACESIZE = 32


class c_tchar(ctypes._SimpleCData):
    if winNT5OrLater:
        _type_ = 'u'  # c_wchar
    else:
        _type_ = 'c'  # c_char


class LOGFONT(Structure):
    _fields_ = [('lfHeight', LONG), ('lfWidth', LONG), ('lfEscapement', LONG),
                ('lfOrientation', LONG),
                ('lfWeight', LONG), ('lfItalic', BYTE), ('lfUnderline', BYTE),
Ejemplo n.º 56
0
 def get_winver():
     maj, min = sys.getwindowsversion()[0:2]
     return '0x0%s' % ((maj * 100) + min)
Ejemplo n.º 57
0
    def _setSystemInfo(self):
        # machine name
        self['systemHostName'] = platform.node()

        self['systemMemTotalRAM'], self['systemMemFreeRAM'] = getRAM()

        # locale information:
        import locale
        loc = '.'.join(map(str, locale.getlocale()))  # (None, None) -> str
        if loc == 'None.None':
            loc = locale.setlocale(locale.LC_ALL, '')
        self[
            'systemLocale'] = loc  # == the locale in use, from OS or user-pref

        # platform name, etc
        if sys.platform in ['darwin']:
            OSXver, junk, architecture = platform.mac_ver()
            platInfo = 'darwin ' + OSXver + ' ' + architecture
            # powerSource = ...
        elif sys.platform in ['linux2']:
            platInfo = 'linux2 ' + platform.release()
            # powerSource = ...
        elif sys.platform in ['win32']:
            platInfo = 'windowsversion=' + repr(sys.getwindowsversion())
            # powerSource = ...
        else:
            platInfo = ' [?]'
            # powerSource = ...
        self['systemPlatform'] = platInfo
        #self['systemPowerSource'] = powerSource

        # count all unique people (user IDs logged in), and find current user name & UID
        self['systemUser'], self['systemUserID'] = _getUserNameUID()
        try:
            users = shellCall("who -q").splitlines()[0].split()
            self['systemUsersCount'] = len(set(users))
        except:
            self['systemUsersCount'] = False

        # when last rebooted?
        try:
            lastboot = shellCall("who -b").split()
            self['systemRebooted'] = ' '.join(lastboot[2:])
        except:  # windows
            sysInfo = shellCall('systeminfo').splitlines()
            lastboot = [
                line for line in sysInfo if line.find("System Up Time") == 0
                or line.find("System Boot Time") == 0
            ]
            lastboot += ['[?]']  # put something in the list just in case
            self['systemRebooted'] = lastboot[0].strip()

        # R (and r2py) for stats:
        try:
            Rver, err = shellCall("R --version", stderr=True)
            Rversion = Rver.splitlines()[0]
            if Rversion.startswith('R version'):
                self['systemRavailable'] = Rversion.strip()
            try:
                import rpy2
                self['systemRpy2'] = rpy2.__version__
            except:
                pass
        except:
            pass

        # encryption / security tools:
        try:
            vers, se = shellCall('openssl version', stderr=True)
            if se:
                vers = str(vers) + se.replace('\n', ' ')[:80]
            if vers.strip():
                self['systemSec.OpenSSLVersion'] = vers
        except:
            pass
        try:
            so, se = shellCall('gpg --version', stderr=True)
            if so.find('GnuPG') > -1:
                self['systemSec.GPGVersion'] = so.splitlines()[0]
                self['systemSec.GPGHome'] = ''.join([
                    line.replace('Home:', '').lstrip()
                    for line in so.splitlines() if line.startswith('Home:')
                ])
        except:
            pass
        try:
            import ssl
            self['systemSec.pythonSSL'] = True
        except ImportError:
            self['systemSec.pythonSSL'] = False

        # pyo for sound:
        try:
            import pyo
            self['systemPyoVersion'] = '%i.%i.%i' % pyo.getVersion()
            try:
                # requires pyo svn r1024 or higher:
                inp, out = pyo.pa_get_devices_infos()
                self['systemPyo.InputDevices'] = inp
                self['systemPyo.OutputDevices'] = out
            except AttributeError:
                pass
        except ImportError:
            pass

        # flac (free lossless audio codec) for google-speech:
        flacv = ''
        if sys.platform != ['win32']:
            flac, se = core.shellCall('which flac', stderr=True)
            if not se and flac and not flac.find('Command not found') > -1:
                flacv = core.shellCall('flac --version')
        else:
            flacexe = 'C:\\Program Files\\FLAC\\flac.exe'
            if os.path.exists(flacexe):
                flacv = core.shellCall(flacexe + ' --version')
        if flacv:
            self['systemFlacVersion'] = flacv

        # detect internet access or fail quickly:
        #web.setupProxy() & web.testProxy(web.proxies)  # can take a long time to fail if there's no connection
        self['systemHaveInternetAccess'] = web.haveInternetAccess()
        if not self['systemHaveInternetAccess']:
            self['systemHaveInternetAccess'] = 'False (proxies not attempted)'
Ejemplo n.º 58
0
def chown(path, user, group=None, pgroup=None, follow_symlinks=True):
    '''
    Chown a file, pass the file the desired user and group

    Under Windows, the group parameter will be ignored.

    This is because while files in Windows do have a 'primary group'
    property, this is rarely used.  It generally has no bearing on
    permissions unless intentionally configured and is most commonly used to
    provide Unix compatibility (e.g. Services For Unix, NFS services).

    If you do want to change the 'primary group' property and understand the
    implications, pass the Windows only parameter, pgroup, instead.

    To set the primary group to 'None', it must be specified in quotes.
    Otherwise Salt will interpret it as the Python value of None and no primary
    group changes will occur. See the example below.

    CLI Example:

    .. code-block:: bash

        salt '*' file.chown c:\\temp\\test.txt myusername
        salt '*' file.chown c:\\temp\\test.txt myusername pgroup=Administrators
        salt '*' file.chown c:\\temp\\test.txt myusername "pgroup='None'"
    '''
    # the group parameter is not used; only provided for API compatibility
    if group:
        func_name = '{0}.chown'.format(__virtualname__)
        if __opts__.get('fun', '') == func_name:
            log.info(
                'The group parameter has no effect when using {0} on Windows '
                'systems; see function docs for details.'.format(func_name))
        log.debug(
            'win_file.py {0} Ignoring the group parameter for {1}'.format(
                func_name, path))
        group = None

    err = ''
    # get SID object for user
    try:
        userSID, domainName, objectType = win32security.LookupAccountName(
            None, user)
    except pywinerror:
        err += 'User does not exist\n'

    if pgroup:
        # get SID object for group
        try:
            groupSID, domainName, objectType = win32security.LookupAccountName(
                None, pgroup)
        except pywinerror:
            err += 'Group does not exist\n'
    else:
        groupSID = None

    if not os.path.exists(path):
        err += 'File not found'
    if err:
        return err

    if follow_symlinks and sys.getwindowsversion().major >= 6:
        path = _resolve_symlink(path)

    privilege_enabled = False
    try:
        privilege_enabled = _enable_privilege(win32security.SE_RESTORE_NAME)
        if pgroup:
            # set owner and group
            win32security.SetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION +
                win32security.GROUP_SECURITY_INFORMATION, userSID, groupSID,
                None, None)
        else:
            # set owner only
            win32security.SetNamedSecurityInfo(
                path, win32security.SE_FILE_OBJECT,
                win32security.OWNER_SECURITY_INFORMATION, userSID, None, None,
                None)
    finally:
        if privilege_enabled:
            _disable_privilege(win32security.SE_RESTORE_NAME)

    return None
Ejemplo n.º 59
0
iswindows = 'win32' in _plat or 'win64' in _plat
isosx     = 'darwin' in _plat
isnewosx  = isosx and getattr(sys, 'new_app_bundle', False)
isfreebsd = 'freebsd' in _plat
isnetbsd = 'netbsd' in _plat
isdragonflybsd = 'dragonfly' in _plat
isbsd = isfreebsd or isnetbsd or isdragonflybsd
ishaiku = 'haiku1' in _plat
islinux   = not(iswindows or isosx or isbsd or ishaiku)
isfrozen  = hasattr(sys, 'frozen')
isunix = isosx or islinux or ishaiku
isportable = os.environ.get('CALIBRE_PORTABLE_BUILD', None) is not None
ispy3 = sys.version_info.major > 2
isxp = isoldvista = False
if iswindows:
    wver = sys.getwindowsversion()
    isxp = wver.major < 6
    isoldvista = wver.build < 6002
is64bit = sys.maxsize > (1 << 32)
isworker = 'CALIBRE_WORKER' in os.environ or 'CALIBRE_SIMPLE_WORKER' in os.environ
if isworker:
    os.environ.pop('CALIBRE_FORCE_ANSI', None)
FAKE_PROTOCOL, FAKE_HOST = 'https', 'calibre-internal.invalid'
VIEWER_APP_UID = u'com.calibre-ebook.viewer'
EDITOR_APP_UID = u'com.calibre-ebook.edit-book'
MAIN_APP_UID = u'com.calibre-ebook.main-gui'
try:
    preferred_encoding = locale.getpreferredencoding()
    codecs.lookup(preferred_encoding)
except:
    preferred_encoding = 'utf-8'
Ejemplo n.º 60
0
    def installZipFile(self, zfile, v=None):
        """If v is provided this will be used as new version number;
        otherwise try and retrieve a version number from zip file name
        """
        info = ""  # return this at the end
        if constants.PY3:
            zfileIsName = type(zfile) == str
        else:
            zfileIsName = type(zfile) in (str, unicode)
        if os.path.isfile(zfile) and zfileIsName:
            # zfile is filename not an actual file
            if v is None:  # try and deduce it
                zFilename = os.path.split(zfile)[-1]
                searchName = re.search('[0-9]*\.[0-9]*\.[0-9]*.', zFilename)
                if searchName != None:
                    v = searchName.group(0)[:-1]
                else:
                    msg = "Couldn't deduce version from zip file: %s"
                    logging.warning(msg % zFilename)
            f = open(zfile, 'rb')
            zfile = zipfile.ZipFile(f)
        else:  # assume here that zfile is a ZipFile
            pass  # todo: error checking - is it a zipfile?

        currPath = self.app.prefs.paths['psychopy']
        currVer = psychopy.__version__
        # any commands that are successfully executed may need to be undone if
        # a later one fails
        undoStr = ""
        # depending on install method, needs diff handling
        # if path ends with 'psychopy' then move it to 'psychopy-version' and
        # create a new 'psychopy' folder for new version
        # does the path contain any version number?
        versionLabelsInPath = re.findall('PsychoPy-.*/', currPath)
        # e.g. the mac standalone app, no need to refer to new version number
        onWin32 = bool(sys.platform == 'win32' and
                       int(sys.getwindowsversion()[1]) > 5)
        if len(versionLabelsInPath) == 0:
            unzipTarget = currPath
            try:  # to move existing PsychoPy
                os.rename(currPath, "%s-%s" % (currPath, currVer))
                undoStr += 'os.rename("%s-%s" %(currPath, currVer),currPath)\n'
            except Exception:
                if onWin32:
                    msg = _translate("To upgrade you need to restart the app"
                                     " as admin (Right-click the app and "
                                     "'Run as admin')")
                else:
                    msg = _translate("Could not move existing PsychoPy "
                                     "installation (permissions error?)")
                return msg
        else:  # setuptools-style installation
            # generate new target path
            unzipTarget = currPath
            for thisVersionLabel in versionLabelsInPath:
                # remove final slash from the re.findall
                pathVersion = thisVersionLabel[:-1]
                unzipTarget = unzipTarget.replace(pathVersion,
                                                  "PsychoPy-%s" % v)
                # find the .pth file that specifies the python dir
                # create the new installation directory BEFORE changing pth
                # file
                nUpdates, newInfo = self.updatePthFile(pathVersion,
                                                       "PsychoPy-%s" % v)
                if nUpdates == -1:  # there was an error (likely permissions)
                    undoStr += 'self.updatePthFile(unzipTarget, currPath)\n'
                    exec(undoStr)  # undo previous changes
                    return newInfo

        try:
            # create the new installation dir AFTER renaming existing dir
            os.makedirs(unzipTarget)
            undoStr += 'os.remove(%s)\n' % unzipTarget
        except Exception:  # revert path rename and inform user
            exec(undoStr)  # undo previous changes
            if onWin32:
                msg = _translate(
                    "Right-click the app and 'Run as admin'):\n%s")
            else:
                msg = _translate("Failed to create directory for new version"
                                 " (permissions error?):\n%s")
            return msg % unzipTarget

        # do the actual extraction
        for name in zfile.namelist():  # for each file within the zip
            # check that this file is part of psychopy (not metadata or docs)
            if name.count('/psychopy/') < 1:
                continue
            try:
                targetFile = os.path.join(unzipTarget,
                                          name.split('/psychopy/')[1])
                targetContainer = os.path.split(targetFile)[0]
                if not os.path.isdir(targetContainer):
                    os.makedirs(targetContainer)  # make the containing folder
                if targetFile.endswith('/'):
                    os.makedirs(targetFile)  # it's a folder
                else:
                    outfile = open(targetFile, 'wb')
                    outfile.write(zfile.read(name))
                    outfile.close()
            except Exception:
                exec(undoStr)  # undo previous changes
                logging.error('failed to unzip file: ' + name)
                logging.error(sys.exc_info()[0])
        info += _translate('Success. \nChanges to PsychoPy will be completed'
                           ' when the application is next run')
        self.cancelBtn.SetDefault()
        self.installBtn.Disable()
        return info