python类platform()的实例源码

profile.py 文件源码 项目:treecat 作者: posterior 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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))
analytics.py 文件源码 项目:PyPlanet 作者: PyPlanet 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
        ))
utils.py 文件源码 项目:LoLVRSpectate 作者: Fire-Proof 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()))
gam.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
gam.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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)
config.py 文件源码 项目:plexivity 作者: mutschler 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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')
utils.py 文件源码 项目:Qyoutube-dl 作者: lzambella 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:Qyoutube-dl 作者: lzambella 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 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

    # 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')
utils.py 文件源码 项目:Qyoutube-dl 作者: lzambella 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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()
process.py 文件源码 项目:monitorstack 作者: openstack 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
system_info.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
system_info.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
system_info.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
implant.py 文件源码 项目:stegator 作者: 1modm 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
#------------------------------------------------------------------------------
implant.py 文件源码 项目:stegator 作者: 1modm 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
#------------------------------------------------------------------------------
utils.py 文件源码 项目:youtube_downloader 作者: aksinghdce 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:youtube_downloader 作者: aksinghdce 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 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

    # 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')
utils.py 文件源码 项目:youtube_downloader 作者: aksinghdce 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()
utils.py 文件源码 项目:youtube_downloader 作者: aksinghdce 项目源码 文件源码 阅读 63 收藏 0 点赞 0 评论 0
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
update.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
ConvertToUTF8.py 文件源码 项目:macos-st-packages 作者: zce 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
update.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
System.py 文件源码 项目:dcmha 作者: wwwbjqcom 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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())
utils.py 文件源码 项目:optimalvibes 作者: littlemika 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:optimalvibes 作者: littlemika 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 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

    # 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')
utils.py 文件源码 项目:optimalvibes 作者: littlemika 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
utils.py 文件源码 项目:optimalvibes 作者: littlemika 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:tvalacarta 作者: tvalacarta 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:tvalacarta 作者: tvalacarta 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 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

    # 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')
utils.py 文件源码 项目:tvalacarta 作者: tvalacarta 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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()


问题


面经


文章

微信
公众号

扫码关注公众号