Python platform 模块,platform() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用platform.platform()

项目:treecat    作者:posterior    | 项目源码 | 文件源码
def run_with_tool(cmd, tool, dirname):
    profile_path = os.path.join(dirname, 'profile_train.prof')
    env = os.environ.copy()
    env['TREECAT_THREADS'] = '1'
    if tool == 'timers':
        env.setdefault('TREECAT_PROFILE', '1')
        env.setdefault('TREECAT_LOG_LEVEL', '20')
        check_call_env([PYTHON, '-O'] + cmd, env)
    elif tool == 'time':
        if platform.platform().startswith('Darwin'):
            gnu_time = 'gtime'
        else:
            gnu_time = '/usr/bin/time'
        check_call_env([gnu_time, '-v', PYTHON, '-O'] + cmd, env)
    elif tool == 'snakeviz':
        check_call_env([PYTHON, '-m', 'cProfile', '-o', profile_path] + cmd,
                       env)
        check_call(['snakeviz', profile_path])
    elif tool == 'line_profiler':
        check_call_env(['kernprof', '-l', '-v', '-o', profile_path] + cmd, env)
    elif tool == 'pdb':
        check_call_env([PYTHON, '-m', 'pdb'] + cmd, env)
    else:
        raise ValueError('Unknown tool: {}'.format(tool))
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def capture(
        self, event_name, event_properties=None
    ):
        event_properties = event_properties or dict()
        user_properties = dict(
            path=self.instance.game.server_path,
            server_name=self.instance.game.server_name,
            language=self.instance.game.server_language,
            login=self.instance.game.server_player_login,
            title=self.instance.game.dedicated_title,
            dedicated_build=self.instance.game.dedicated_build,
            dedicated_version=self.instance.game.dedicated_version,
        )

        await self.execute(dict(
            user_id=self.instance.game.server_player_login,
            event_type=event_name, event_properties=event_properties, user_properties=user_properties,
            app_version=version, platform=platform.platform(), os_name=platform.system(), os_version=platform.version(),
            language=self.instance.game.server_language
        ))
项目:LoLVRSpectate    作者:Fire-Proof    | 项目源码 | 文件源码
def setup_logging(debug=False, os_info=True):
    if os.environ.get("LOLVRSPECTATE_DEBUG") == "1":
        debug = True

    if not debug:
        format_ = '%(asctime)-15s || %(message)s'
        logging.basicConfig(filename="LoLVRSpectate.log", format=format_, level=logging.INFO, filemode="w")
        logging.getLogger().addHandler(logging.StreamHandler())  # Log both to file and console
    else:
        logging.basicConfig(level=logging.DEBUG)

    if os_info:
        logging.info("Win platform = {}".format(platform.platform()))
        if 'PROGRAMFILES(X86)' in os.environ:
            logging.info("System Arch = {}".format("64 bit"))
        else:
            logging.info("System Arch = {}".format("32 bit"))
        logging.info("Python version = {}".format(sys.version))
        logging.info("VorpX exclusion = {}".format(is_excluded()))
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def doVersion(checkForArgs=True):
  forceCheck = simple = False
  if checkForArgs:
    while Cmd.ArgumentsRemaining():
      myarg = getArgument()
      if myarg == u'check':
        forceCheck = True
      elif myarg == u'simple':
        simple = True
      else:
        unknownArgumentExit()
  if simple:
    writeStdout(__version__)
    return
  import struct
  version_data = u'GAM {0} - {1}\n{2}\nPython {3}.{4}.{5} {6}-bit {7}\ngoogle-api-python-client {8}\noauth2client {9}\n{10} {11}\nPath: {12}\n'
  writeStdout(version_data.format(__version__, GAM_URL, __author__, sys.version_info[0],
                                  sys.version_info[1], sys.version_info[2], struct.calcsize(u'P')*8,
                                  sys.version_info[3], googleapiclient.__version__, oauth2client.__version__, platform.platform(),
                                  platform.machine(), GM.Globals[GM.GAM_PATH]))
  if forceCheck:
    doGAMCheckForUpdates(forceCheck=True)

# gam help
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getCRMService(login_hint):
  from oauth2client.contrib.dictionary_storage import DictionaryStorage
  scope = u'https://www.googleapis.com/auth/cloud-platform'
  client_id = u'297408095146-fug707qsjv4ikron0hugpevbrjhkmsk7.apps.googleusercontent.com'
  client_secret = u'qM3dP8f_4qedwzWQE1VR4zzU'
  flow = oauth2client.client.OAuth2WebServerFlow(client_id=client_id,
                                                 client_secret=client_secret, scope=scope, redirect_uri=oauth2client.client.OOB_CALLBACK_URN,
                                                 user_agent=GAM_INFO, access_type=u'online', response_type=u'code', login_hint=login_hint)
  storage_dict = {}
  storage = DictionaryStorage(storage_dict, u'credentials')
  flags = cmd_flags(noLocalWebserver=GC.Values[GC.NO_BROWSER])
  httpObj = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL])
  try:
    credentials = oauth2client.tools.run_flow(flow=flow, storage=storage, flags=flags, http=httpObj)
  except httplib2.CertificateValidationUnsupported:
    noPythonSSLExit()
  credentials.user_agent = GAM_INFO
  httpObj = credentials.authorize(httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL],
                                                cache=None))
  return (googleapiclient.discovery.build(u'cloudresourcemanager', u'v1', http=httpObj, cache_discovery=False), httpObj)
项目:plexivity    作者:mutschler    | 项目源码 | 文件源码
def getDataDir():

    # Windows
    if os.name == 'nt':
        return os.path.join(os.environ['APPDATA'], 'plexivity')

    user_dir = getUserDir()

    # OSX
    if 'darwin' in platform.platform().lower():
        return os.path.join(user_dir, 'Library', 'Application Support', 'plexivity')

    # FreeBSD
    if 'freebsd' in sys.platform:
        return os.path.join('/usr/local/', 'plexivity', 'data')

    # Linux
    return os.path.join(user_dir, '.plexivity')
项目:Qyoutube-dl    作者:lzambella    | 项目源码 | 文件源码
def sanitize_path(s):
    """Sanitizes and normalizes path on Windows"""
    if sys.platform != 'win32':
        return s
    drive_or_unc, _ = os.path.splitdrive(s)
    if sys.version_info < (2, 7) and not drive_or_unc:
        drive_or_unc, _ = os.path.splitunc(s)
    norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
    if drive_or_unc:
        norm_path.pop(0)
    sanitized_path = [
        path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
        for path_part in norm_path]
    if drive_or_unc:
        sanitized_path.insert(0, drive_or_unc + os.path.sep)
    return os.path.join(*sanitized_path)


# Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
# unwanted failures due to missing protocol
项目:Qyoutube-dl    作者:lzambella    | 项目源码 | 文件源码
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

    # Pass '' 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 and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    return s.encode(get_subprocess_encoding(), 'ignore')
项目:Qyoutube-dl    作者:lzambella    | 项目源码 | 文件源码
def write_string(s, out=None, encoding=None):
    if out is None:
        out = sys.stderr
    assert type(s) == compat_str

    if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
        if _windows_write_string(s, out):
            return

    if ('b' in getattr(out, 'mode', '') or
            sys.version_info[0] < 3):  # Python 2 lies about mode of sys.stderr
        byt = s.encode(encoding or preferredencoding(), 'ignore')
        out.write(byt)
    elif hasattr(out, 'buffer'):
        enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
        byt = s.encode(enc, 'ignore')
        out.buffer.write(byt)
    else:
        out.write(s)
    out.flush()
项目:monitorstack    作者:openstack    | 项目源码 | 文件源码
def cli(ctx, process_name):
    """Check if a process is running."""
    setattr(cli, '__doc__', DOC)

    output = {
        'exit_code': 0,
        'message': 'process check is ok',
        'measurement_name': 'process',
        'meta': {
            'platform': platform.platform(),
        },
        'variables': {}
    }

    if check_process(process_name):
        output['variables'] = {process_name: 1}
    else:
        output['exit_code'] = 1
        output['message'] = '{} failed -- Process {} not found'.format(
            COMMAND_NAME,
            process_name
        )
        output['variables'] = {process_name: 0}

    return output
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def _lib_list(self, lib_dir, libs, exts):
        assert is_string(lib_dir)
        liblist = []
        # under windows first try without 'lib' prefix
        if sys.platform == 'win32':
            lib_prefixes = ['', 'lib']
        else:
            lib_prefixes = ['lib']
        # for each library name, see if we can find a file for it.
        for l in libs:
            for ext in exts:
                for prefix in lib_prefixes:
                    p = self.combine_paths(lib_dir, prefix + l + ext)
                    if p:
                        break
                if p:
                    assert len(p) == 1
                    # ??? splitext on p[0] would do this for cygwin
                    # doesn't seem correct
                    if ext == '.dll.a':
                        l += '.dll'
                    liblist.append(l)
                    break
        return liblist
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def calc_info(self):
        lib_dirs = self.get_lib_dirs()
        incl_dirs = self.get_include_dirs()
        mkl_libs = self.get_libs('mkl_libs', self._lib_mkl)
        info = self.check_libs2(lib_dirs, mkl_libs)
        if info is None:
            return
        dict_append(info,
                    define_macros=[('SCIPY_MKL_H', None),
                                   ('HAVE_CBLAS', None)],
                    include_dirs=incl_dirs)
        if sys.platform == 'win32':
            pass  # win32 has no pthread library
        else:
            dict_append(info, libraries=['pthread'])
        self.set_info(**info)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def calc_info(self):
        if sys.platform  in ['win32']:
            return
        lib_dirs = self.get_lib_dirs()
        include_dirs = self.get_include_dirs()
        x11_libs = self.get_libs('x11_libs', ['X11'])
        info = self.check_libs(lib_dirs, x11_libs, [])
        if info is None:
            return
        inc_dir = None
        for d in include_dirs:
            if self.combine_paths(d, 'X11/X.h'):
                inc_dir = d
                break
        if inc_dir is not None:
            dict_append(info, include_dirs=[inc_dir])
        self.set_info(**info)
项目:stegator    作者:1modm    | 项目源码 | 文件源码
def build(self):
        if (any(platform.win32_ver())):
            stroutput = self.remove_accents(self.output)
        else:
            stroutput = self.output

        cmd = {'sender': self.sender,
                'receiver': self.receiver,
                'output': stroutput,
                'cmd': self.cmd,
                'jobid': self.jobid}
        return base64.b64encode(json.dumps(cmd))


#------------------------------------------------------------------------------
# Class ChromePasswords
#------------------------------------------------------------------------------
项目:stegator    作者:1modm    | 项目源码 | 文件源码
def run(self):
        output = None
        if (self.command == 'PING'):
            output = platform.platform()
        else:
            try:
                output = subprocess.check_output(self.command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
            except:
                print((colored('[-] Error executing the command' , 'yellow')))

        output_command = CommandOutput(MAC_ADDRESS, 'master', output, self.jobid, self.command)

        saveimg = ImageHandle()

        # Trying to save image until True
        saveimageOutput = False
        while not (saveimageOutput):
            saveimageOutput = saveimg.save(output_command.build(), self.jobid)


#------------------------------------------------------------------------------
# Class StdOutListener: listener to intercept messages
#------------------------------------------------------------------------------
项目:youtube_downloader    作者:aksinghdce    | 项目源码 | 文件源码
def sanitize_path(s):
    """Sanitizes and normalizes path on Windows"""
    if sys.platform != 'win32':
        return s
    drive_or_unc, _ = os.path.splitdrive(s)
    if sys.version_info < (2, 7) and not drive_or_unc:
        drive_or_unc, _ = os.path.splitunc(s)
    norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
    if drive_or_unc:
        norm_path.pop(0)
    sanitized_path = [
        path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
        for path_part in norm_path]
    if drive_or_unc:
        sanitized_path.insert(0, drive_or_unc + os.path.sep)
    return os.path.join(*sanitized_path)


# Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
# unwanted failures due to missing protocol
项目:youtube_downloader    作者:aksinghdce    | 项目源码 | 文件源码
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

    # Pass '' 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 and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
    if sys.platform.startswith('java'):
        return s

    return s.encode(get_subprocess_encoding(), 'ignore')
项目:youtube_downloader    作者:aksinghdce    | 项目源码 | 文件源码
def write_string(s, out=None, encoding=None):
    if out is None:
        out = sys.stderr
    assert type(s) == compat_str

    if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
        if _windows_write_string(s, out):
            return

    if ('b' in getattr(out, 'mode', '') or
            sys.version_info[0] < 3):  # Python 2 lies about mode of sys.stderr
        byt = s.encode(encoding or preferredencoding(), 'ignore')
        out.write(byt)
    elif hasattr(out, 'buffer'):
        enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
        byt = s.encode(enc, 'ignore')
        out.buffer.write(byt)
    else:
        out.write(s)
    out.flush()
项目:youtube_downloader    作者:aksinghdce    | 项目源码 | 文件源码
def setproctitle(title):
    assert isinstance(title, compat_str)

    # ctypes in Jython is not complete
    # http://bugs.jython.org/issue2148
    if sys.platform.startswith('java'):
        return

    try:
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
    except OSError:
        return
    except TypeError:
        # LoadLibrary in Windows Python 2.7.13 only expects
        # a bytestring, but since unicode_literals turns
        # every string into a unicode string, it fails.
        return
    title_bytes = title.encode('utf-8')
    buf = ctypes.create_string_buffer(len(title_bytes))
    buf.value = title_bytes
    try:
        libc.prctl(15, buf, 0, 0, 0)
    except AttributeError:
        return  # Strange libc, just skip this
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def create_desktop_shortcut():
    import sys
    if sys.platform.startswith("linux"):
        pass
    elif sys.platform == "win32":
        # import ctypes
        # msg = u"??????????"
        # title = u"XX-Net ???"
        #res = ctypes.windll.user32.MessageBoxW(None, msg, title, 1)
        # Yes:1 No:2
        #if res == 2:
        #    return
        work_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(work_path)

        import subprocess
        subprocess.call(["Wscript.exe", "//E:JScript", "create_shortcut.js"], shell=False)
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
def run(self, edit, encoding, file_name, need_codecs):
        self.view.set_name('ConvertToUTF8 Instructions')
        self.view.set_scratch(True)
        self.view.settings().set("word_wrap", True)
        msg = 'File: {0}\nEncoding: {1}\nError: '.format(file_name, encoding)
        if need_codecs:
            msg = msg + 'Codecs missing\n\n'
            branch = self.get_branch(sublime.platform(), sublime.arch())
            if branch:
                ver = '33' if ST3 else '26'
                msg = msg + 'Please install Codecs{0} plugin (https://github.com/seanliang/Codecs{0}/tree/{1}).\n'.format(ver, branch)
            else:
                import platform
                msg = msg + 'Please send the following information to sunlxy (at) yahoo.com:\n====== Debug Information ======\nVersion: {0}-{1}\nPlatform: {2}\nPath: {3}\nEncoding: {4}\n'.format(
                    sublime.version(), sublime.arch(), platform.platform(), sys.path, encoding
                )
        else:
            msg = msg + 'Unsupported encoding, see http://docs.python.org/library/codecs.html#standard-encodings\n\nPlease try other tools such as iconv.\n'

        self.view.insert(edit, 0, msg)
        self.view.set_read_only(True)
        self.view.window().focus_view(self.view)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def create_desktop_shortcut():
    import sys
    if sys.platform.startswith("linux"):
        pass
    elif sys.platform == "win32":
        # import ctypes
        # msg = u"??????????"
        # title = u"XX-Net ???"
        #res = ctypes.windll.user32.MessageBoxW(None, msg, title, 1)
        # Yes:1 No:2
        #if res == 2:
        #    return
        work_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(work_path)

        import subprocess
        subprocess.call(["Wscript.exe", "//E:JScript", "create_shortcut.js"], shell=False)
项目:dcmha    作者:wwwbjqcom    | 项目源码 | 文件源码
def TestPlatform():
    print ("----------Operation System--------------------------")
    # Windows will be : (32bit, WindowsPE)
    # Linux will be : (32bit, ELF)
    print(platform.architecture())

    # Windows will be : Windows-XP-5.1.2600-SP3 or Windows-post2008Server-6.1.7600
    # Linux will be : Linux-2.6.18-128.el5-i686-with-redhat-5.3-Final
    print(platform.platform())

    # Windows will be : Windows
    # Linux will be : Linux
    print(platform.system())

    print ("--------------Python Version-------------------------")
    # Windows and Linux will be : 3.1.1 or 3.1.3
    print(platform.python_version())
项目:optimalvibes    作者:littlemika    | 项目源码 | 文件源码
def sanitize_path(s):
    """Sanitizes and normalizes path on Windows"""
    if sys.platform != 'win32':
        return s
    drive_or_unc, _ = os.path.splitdrive(s)
    if sys.version_info < (2, 7) and not drive_or_unc:
        drive_or_unc, _ = os.path.splitunc(s)
    norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
    if drive_or_unc:
        norm_path.pop(0)
    sanitized_path = [
        path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
        for path_part in norm_path]
    if drive_or_unc:
        sanitized_path.insert(0, drive_or_unc + os.path.sep)
    return os.path.join(*sanitized_path)


# Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
# unwanted failures due to missing protocol
项目:optimalvibes    作者:littlemika    | 项目源码 | 文件源码
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

    # Pass '' 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 and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
    if sys.platform.startswith('java'):
        return s

    return s.encode(get_subprocess_encoding(), 'ignore')
项目:optimalvibes    作者:littlemika    | 项目源码 | 文件源码
def write_string(s, out=None, encoding=None):
    if out is None:
        out = sys.stderr
    assert type(s) == compat_str

    if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
        if _windows_write_string(s, out):
            return

    if ('b' in getattr(out, 'mode', '') or
            sys.version_info[0] < 3):  # Python 2 lies about mode of sys.stderr
        byt = s.encode(encoding or preferredencoding(), 'ignore')
        out.write(byt)
    elif hasattr(out, 'buffer'):
        enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
        byt = s.encode(enc, 'ignore')
        out.buffer.write(byt)
    else:
        out.write(s)
    out.flush()
项目:optimalvibes    作者:littlemika    | 项目源码 | 文件源码
def setproctitle(title):
    assert isinstance(title, compat_str)

    # ctypes in Jython is not complete
    # http://bugs.jython.org/issue2148
    if sys.platform.startswith('java'):
        return

    try:
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
    except OSError:
        return
    except TypeError:
        # LoadLibrary in Windows Python 2.7.13 only expects
        # a bytestring, but since unicode_literals turns
        # every string into a unicode string, it fails.
        return
    title_bytes = title.encode('utf-8')
    buf = ctypes.create_string_buffer(len(title_bytes))
    buf.value = title_bytes
    try:
        libc.prctl(15, buf, 0, 0, 0)
    except AttributeError:
        return  # Strange libc, just skip this
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def sanitize_path(s):
    """Sanitizes and normalizes path on Windows"""
    if sys.platform != 'win32':
        return s
    drive_or_unc, _ = os.path.splitdrive(s)
    if sys.version_info < (2, 7) and not drive_or_unc:
        drive_or_unc, _ = os.path.splitunc(s)
    norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
    if drive_or_unc:
        norm_path.pop(0)
    sanitized_path = [
        path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
        for path_part in norm_path]
    if drive_or_unc:
        sanitized_path.insert(0, drive_or_unc + os.path.sep)
    return os.path.join(*sanitized_path)


# Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
# unwanted failures due to missing protocol
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
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

    # Pass '' 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 and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        return s

    # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
    if sys.platform.startswith('java'):
        return s

    return s.encode(get_subprocess_encoding(), 'ignore')
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def write_string(s, out=None, encoding=None):
    if out is None:
        out = sys.stderr
    assert type(s) == compat_str

    if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
        if _windows_write_string(s, out):
            return

    if ('b' in getattr(out, 'mode', '') or
            sys.version_info[0] < 3):  # Python 2 lies about mode of sys.stderr
        byt = s.encode(encoding or preferredencoding(), 'ignore')
        out.write(byt)
    elif hasattr(out, 'buffer'):
        enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
        byt = s.encode(enc, 'ignore')
        out.buffer.write(byt)
    else:
        out.write(s)
    out.flush()
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def setproctitle(title):
    assert isinstance(title, compat_str)

    # ctypes in Jython is not complete
    # http://bugs.jython.org/issue2148
    if sys.platform.startswith('java'):
        return

    try:
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
    except OSError:
        return
    except TypeError:
        # LoadLibrary in Windows Python 2.7.13 only expects
        # a bytestring, but since unicode_literals turns
        # every string into a unicode string, it fails.
        return
    title_bytes = title.encode('utf-8')
    buf = ctypes.create_string_buffer(len(title_bytes))
    buf.value = title_bytes
    try:
        libc.prctl(15, buf, 0, 0, 0)
    except AttributeError:
        return  # Strange libc, just skip this
项目:tcex    作者:ThreatConnect-Inc    | 项目源码 | 文件源码
def results_tc(self, key, value):
        """Write data to results_tc file in TcEX specified directory

        The TcEx platform support persistent values between executions of the App.  This
        method will store the values for TC to read and put into the Database.

        Args:
            key (string): The data key to be stored
            value (string): The data value to be stored
        """
        if os.access(self.default_args.tc_out_path, os.W_OK):
            result_file = '{}/results.tc'.format(self.default_args.tc_out_path)
        else:
            result_file = 'results.tc'

        results = '{} = {}\n'.format(key, value)
        with open(result_file, 'a') as rh:
            rh.write(results)
项目:tcex    作者:ThreatConnect-Inc    | 项目源码 | 文件源码
def results_tc_args(self):
        """Read data from results_tc file from previous run of app.

        This method is only required when not running from the with the
        TcEX platform and is only intended for testing apps locally.

        Returns:
            (dictionary): A dictionary of values written to results_tc.
        """
        results = []
        if os.access(self.default_args.tc_out_path, os.W_OK):
            result_file = '{}/results.tc'.format(self.default_args.tc_out_path)
        else:
            result_file = 'results.tc'

        if os.path.isfile(result_file):
            with open(result_file, 'r') as rh:
                results = rh.read().strip().split('\n')
            os.remove(result_file)

        for line in results:
            key, value = line.split(' = ')
            setattr(self.default_args, key, value)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def sys_info():
    """Return useful information about IPython and the system, as a string.

    Examples
    --------
    ::

        In [2]: print sys_info()
        {'commit_hash': '144fdae',      # random
         'commit_source': 'repository',
         'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
         'ipython_version': '0.11.dev',
         'os_name': 'posix',
         'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick',
         'sys_executable': '/usr/bin/python',
         'sys_platform': 'linux2',
         'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
    """
    return pprint.pformat(get_sys_info())
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_architecture_via_symlink(self): # issue3762
        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
        # to add the directory to the path.
        if sys.platform == "win32":
            os.environ["Path"] = "{};{}".format(
                os.path.dirname(sys.executable), os.environ["Path"])

        def get(python):
            cmd = [python, '-c',
                'import platform; print(platform.architecture())']
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            return p.communicate()
        real = os.path.realpath(sys.executable)
        link = os.path.abspath(support.TESTFN)
        os.symlink(real, link)
        try:
            self.assertEqual(get(real), get(link))
        finally:
            os.remove(link)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_uname_win32_ARCHITEW6432(self):
        # Issue 7860: make sure we get architecture from the correct variable
        # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
        # using it, per
        # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
        try:
            with support.EnvironmentVarGuard() as environ:
                if 'PROCESSOR_ARCHITEW6432' in environ:
                    del environ['PROCESSOR_ARCHITEW6432']
                environ['PROCESSOR_ARCHITECTURE'] = 'foo'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'foo')
                environ['PROCESSOR_ARCHITEW6432'] = 'bar'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'bar')
        finally:
            platform._uname_cache = None
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_parse_release_file(self):

        for input, output in (
            # Examples of release file contents:
            ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')),
            ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64')),
            ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586')),
            ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux')),
            ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche')),
            ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike')),
            ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant')),
            ('CentOS release 4', ('CentOS', '4', None)),
            ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')),
            ('', ('', '', '')), # If there's nothing there.
            ):
            self.assertEqual(platform._parse_release_file(input), output)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def _lib_list(self, lib_dir, libs, exts):
        assert is_string(lib_dir)
        liblist = []
        # under windows first try without 'lib' prefix
        if sys.platform == 'win32':
            lib_prefixes = ['', 'lib']
        else:
            lib_prefixes = ['lib']
        # for each library name, see if we can find a file for it.
        for l in libs:
            for ext in exts:
                for prefix in lib_prefixes:
                    p = self.combine_paths(lib_dir, prefix + l + ext)
                    if p:
                        break
                if p:
                    assert len(p) == 1
                    # ??? splitext on p[0] would do this for cygwin
                    # doesn't seem correct
                    if ext == '.dll.a':
                        l += '.dll'
                    liblist.append(l)
                    break
        return liblist
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def calc_info(self):
        lib_dirs = self.get_lib_dirs()
        incl_dirs = self.get_include_dirs()
        mkl_libs = self.get_libs('mkl_libs', self._lib_mkl)
        info = self.check_libs2(lib_dirs, mkl_libs)
        if info is None:
            return
        dict_append(info,
                    define_macros=[('SCIPY_MKL_H', None),
                                   ('HAVE_CBLAS', None)],
                    include_dirs=incl_dirs)
        if sys.platform == 'win32':
            pass  # win32 has no pthread library
        else:
            dict_append(info, libraries=['pthread'])
        self.set_info(**info)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def calc_info(self):
        if sys.platform  in ['win32']:
            return
        lib_dirs = self.get_lib_dirs()
        include_dirs = self.get_include_dirs()
        x11_libs = self.get_libs('x11_libs', ['X11'])
        info = self.check_libs(lib_dirs, x11_libs, [])
        if info is None:
            return
        inc_dir = None
        for d in include_dirs:
            if self.combine_paths(d, 'X11/X.h'):
                inc_dir = d
                break
        if inc_dir is not None:
            dict_append(info, include_dirs=[inc_dir])
        self.set_info(**info)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_uname_win32_ARCHITEW6432(self):
        # Issue 7860: make sure we get architecture from the correct variable
        # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
        # using it, per
        # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
        try:
            with test_support.EnvironmentVarGuard() as environ:
                if 'PROCESSOR_ARCHITEW6432' in environ:
                    del environ['PROCESSOR_ARCHITEW6432']
                environ['PROCESSOR_ARCHITECTURE'] = 'foo'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'foo')
                environ['PROCESSOR_ARCHITEW6432'] = 'bar'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'bar')
        finally:
            platform._uname_cache = None
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_mac_ver_with_fork(self):
        # Issue7895: platform.mac_ver() crashes when using fork without exec
        #
        # This test checks that the fix for that issue works.
        #
        pid = os.fork()
        if pid == 0:
            # child
            info = platform.mac_ver()
            os._exit(0)

        else:
            # parent
            cpid, sts = os.waitpid(pid, 0)
            self.assertEqual(cpid, pid)
            self.assertEqual(sts, 0)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_parse_release_file(self):

        for input, output in (
            # Examples of release file contents:
            ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')),
            ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64')),
            ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586')),
            ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux')),
            ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche')),
            ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike')),
            ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant')),
            ('CentOS release 4', ('CentOS', '4', None)),
            ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')),
            ('', ('', '', '')), # If there's nothing there.
            ):
            self.assertEqual(platform._parse_release_file(input), output)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def print_machine_details(d, indent=''):

    l = ['Machine Details:',
         '   Platform ID:    %s' % d.get('platform', 'n/a'),
         '   Processor:      %s' % d.get('processor', 'n/a'),
         '',
         'Python:',
         '   Implementation: %s' % d.get('implementation', 'n/a'),
         '   Executable:     %s' % d.get('executable', 'n/a'),
         '   Version:        %s' % d.get('python', 'n/a'),
         '   Compiler:       %s' % d.get('compiler', 'n/a'),
         '   Bits:           %s' % d.get('bits', 'n/a'),
         '   Build:          %s (#%s)' % (d.get('builddate', 'n/a'),
                                          d.get('buildno', 'n/a')),
         '   Unicode:        %s' % d.get('unicode', 'n/a'),
         ]
    print indent + string.join(l, '\n' + indent) + '\n'

### Test baseclass
项目:AutoML5    作者:djajetic    | 项目源码 | 文件源码
def show_platform():
    ''' Show information on platform'''
    swrite('\n=== SYSTEM ===\n\n')
    try:
        linux_distribution = platform.linux_distribution()
    except:
        linux_distribution = "N/A"
    swrite("""
    dist: %s
    linux_distribution: %s
    system: %s
    machine: %s
    platform: %s
    uname: %s
    version: %s
    mac_ver: %s
    memory: %s
    number of CPU: %s
    """ % (
    str(platform.dist()),
    linux_distribution,
    platform.system(),
    platform.machine(),
    platform.platform(),
    platform.uname(),
    platform.version(),
    platform.mac_ver(),
    psutil.virtual_memory(),
    str(psutil.cpu_count())
    ))
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def add_run_main():
    if sys.platform.startswith('darwin'):
        return '''
class AppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, notification):
        st_thread = threading.Thread(target=main)
        st_thread.daemon = True
        st_thread.start()

def osx_main():
    app = NSApplication.sharedApplication()
    delegate = AppDelegate.alloc().init()
    NSApp().setDelegate_(delegate)
    AppHelper.runEventLoop()

if __name__ == '__main__':
    osx_main()
'''
    else:
        return '''
if __name__ == '__main__':
    main()
'''
################################################################################
#                       st_utils.py stitch_gen variables                       #
################################################################################
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def get_requirements():
    return '''
import os
import re
import sys
import math
import time
import socket
import base64
import shutil
import ctypes
import socket
import struct
import zipfile
import datetime
import requests
import StringIO
import platform
import threading
import subprocess
from Crypto import Random
from Crypto.Cipher import AES
from mss import ScreenshotError
from time import strftime, sleep
from contextlib import contextmanager
from base64 import b64decode as INFO
from zlib import decompress as SEC

from st_utils import *
from st_protocol import *
from st_encryption import *
'''
项目:docklet    作者:unias    | 项目源码 | 文件源码
def collect_osinfo(self):
        uname = platform.uname()
        osinfo = {}
        osinfo['platform'] = platform.platform()
        osinfo['system'] = uname.system
        osinfo['node'] = uname.node
        osinfo['release'] = uname.release
        osinfo['version'] = uname.version
        osinfo['machine'] = uname.machine
        osinfo['processor'] = uname.processor
        return osinfo

    # run function in the thread