当前位置: 首页>>代码示例>>Python>>正文


Python msvcrt.setmode函数代码示例

本文整理汇总了Python中msvcrt.setmode函数的典型用法代码示例。如果您正苦于以下问题:Python setmode函数的具体用法?Python setmode怎么用?Python setmode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了setmode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handleRequest

    def handleRequest(self, fin=None, fout=None, env=None):
        if fin==None:
            fin = sys.stdin
        if fout==None:
            fout = sys.stdout
        if env == None:
            env = os.environ
        
        try:
            contLen=int(env['CONTENT_LENGTH'])
            data = fin.read(contLen)
        except Exception:
            data = ""

        resultData = ServiceHandler.handleRequest(self, data)
        
        response = "Content-Type: text/plain\n"
        response += "Content-Length: %d\n\n" % len(resultData)
        response += resultData
        
        #on windows all \n are converted to \r\n if stdout is a terminal and  is not set to binary mode :(
        #this will then cause an incorrect Content-length.
        #I have only experienced this problem with apache on Win so far.
        if sys.platform == "win32":
            try:
                import  msvcrt
                msvcrt.setmode(fout.fileno(), os.O_BINARY)
            except:
                pass
        #put out the response
        fout.write(response)
        fout.flush()
开发者ID:mungerd,项目名称:latbuilder,代码行数:32,代码来源:cgiwrapper.py

示例2: __init__

    def __init__(self, proto):
        """
        Start talking to standard IO with the given protocol.

        Also, put it stdin/stdout/stderr into binary mode.
        """
        from twisted.internet import reactor

        for stdfd in range(0, 1, 2):
            msvcrt.setmode(stdfd, os.O_BINARY)

        _pollingfile._PollingTimer.__init__(self, reactor)
        self.proto = proto

        hstdin = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
        hstdout = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)

        self.stdin = _pollingfile._PollableReadPipe(
            hstdin, self.dataReceived, self.readConnectionLost)

        self.stdout = _pollingfile._PollableWritePipe(
            hstdout, self.writeConnectionLost)

        self._addPollableResource(self.stdin)
        self._addPollableResource(self.stdout)

        self.proto.makeConnection(self)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:27,代码来源:_win32stdio.py

示例3: main

def main():
    optparser = optparse.OptionParser(
        usage="\n\tapitrace pickle <trace> | %prog [options]")
    optparser.add_option(
        '-p', '--profile',
        action="store_true", dest="profile", default=False,
        help="profile call parsing")
    optparser.add_option(
        '-v', '--verbose',
        action="store_true", dest="verbose", default=False,
        help="dump calls to stdout")

    (options, args) = optparser.parse_args(sys.argv[1:])

    if args:
        optparser.error('unexpected arguments')

    # Change stdin to binary mode
    try:
        import msvcrt
    except ImportError:
        pass
    else:
        import os
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)

    startTime = time.time()
    parser = Counter(sys.stdin.buffer, options.verbose)
    parser.parse()
    stopTime = time.time()
    duration = stopTime - startTime

    if options.profile:
        sys.stderr.write('Processed %u calls in %.03f secs, at %u calls/sec\n' % (parser.numCalls, duration, parser.numCalls/duration))
开发者ID:apitrace,项目名称:apitrace,代码行数:34,代码来源:unpickle.py

示例4: sanitize_open

def sanitize_open(filename, open_mode):
	"""Try to open the given filename, and slightly tweak it if this fails.

	Attempts to open the given filename. If this fails, it tries to change
	the filename slightly, step by step, until it's either able to open it
	or it fails and raises a final exception, like the standard open()
	function.

	It returns the tuple (stream, definitive_file_name).
	"""
	try:
		if filename == u'-':
			if sys.platform == 'win32':
				import msvcrt
				msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
			return (sys.stdout, filename)
		stream = open(encodeFilename(filename), open_mode)
		return (stream, filename)
	except (IOError, OSError), err:
		# In case of error, try to remove win32 forbidden chars
		filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)

		# An exception here should be caught in the caller
		stream = open(encodeFilename(filename), open_mode)
		return (stream, filename)
开发者ID:Asido,项目名称:youtube-dl,代码行数:25,代码来源:utils.py

示例5: run

    def run(self):
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        stdin = sys.stdin
        stdout = os.fdopen(sys.stdin.fileno(), 'w', 0)

        conn = Connection(stdin, stdout, self)
        conn.run()
开发者ID:alexsilva,项目名称:helicon-zoofcgi,代码行数:7,代码来源:zoofcgi.py

示例6: Translate

def Translate(filenameInput, commandPython, options):
    if filenameInput == '':
        if sys.platform == 'win32':
            import msvcrt
            msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        fIn = sys.stdin
    else:
        fIn = open(filenameInput, 'rb')

    if options.output == '':
        if sys.platform == 'win32':
            import msvcrt
            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
        fOut = sys.stdout
    else:
        fOut = open(options.output, 'wb')

    if options.script != '':
        execfile(options.script, globals())

    if options.fullread:
        fOut.write(eval(commandPython)(fIn.read()))
    else:
        Transform(fIn, fOut, commandPython)

    if fIn != sys.stdin:
        fIn.close()
    if fOut != sys.stdout:
        fOut.close()
开发者ID:danielgindi,项目名称:DidierStevensSuite,代码行数:29,代码来源:translate.py

示例7: upload

def upload(filenm, path):

    try: # Windows needs stdio set for binary mode.
        import msvcrt
        msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
        msvcrt.setmode (1, os.O_BINARY) # stdout = 1
    except ImportError:
        pass

    fileitem = filenm
    root_path = path

    # Test if the file was uploaded
    if fileitem.filename:

        # strip leading path from file name to avoid directory traversal attacks
        fn = os.path.basename(fileitem.filename)
        f = open(root_path + fn, 'wb', 10000)

        # Read the file in chunks
        for chunk in fbuffer(fileitem.file):
            f.write(chunk)
        f.close()
        return 'The file "' + fn + '" was uploaded successfully'

    else:
        return 'No file was uploaded'
开发者ID:pybokeh,项目名称:python,代码行数:27,代码来源:www.py

示例8: __init__

 def __init__(self, infile, outfile):
     if sys.platform == 'win32':
         import msvcrt
         msvcrt.setmode(infile.fileno(), os.O_BINARY)
         msvcrt.setmode(outfile.fileno(), os.O_BINARY)
     self.outfile, self.infile = infile, outfile
     self.readable = self.writeable = True
开发者ID:TheDunn,项目名称:flex-pypy,代码行数:7,代码来源:inputoutput.py

示例9: __init__

 def __init__(self, f_in, f_out):
     if sys.platform == 'win32':
         import msvcrt
         msvcrt.setmode(f_in.fileno(), os.O_BINARY)
         msvcrt.setmode(f_out.fileno(), os.O_BINARY)
     self.f_in = f_in
     self.f_out = f_out
开发者ID:TheDunn,项目名称:flex-pypy,代码行数:7,代码来源:msgstruct.py

示例10: listen

    def listen(self):
        stdout = sys.stdout
        # Mute stdout. Nobody should actually be able to write to it,
        # because stdout is used for IPC.
        sys.stdout = open(os.devnull, 'w')
        stdin = sys.stdin
        if sys.version_info[0] > 2:
            stdout = stdout.buffer
            stdin = stdin.buffer
        # Python 2 opens streams in text mode on Windows. Set stdout and stdin
        # to binary mode.
        elif sys.platform == 'win32':
            import msvcrt
            msvcrt.setmode(stdout.fileno(), os.O_BINARY)
            msvcrt.setmode(stdin.fileno(), os.O_BINARY)

        while True:
            try:
                payload = pickle_load(stdin)
            except EOFError:
                # It looks like the parent process closed.
                # Don't make a big fuss here and just exit.
                exit(0)
            try:
                result = False, None, self._run(*payload)
            except Exception as e:
                result = True, traceback.format_exc(), e

            pickle_dump(result, stdout, self._pickle_protocol)
开发者ID:BlackArch,项目名称:blackarch-iso,代码行数:29,代码来源:__init__.py

示例11: stdout_to_binary

def stdout_to_binary():
    """
    Ensure that stdout is in binary mode on windows
    """
    if sys.platform == 'win32':
        import msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
开发者ID:Perfit-labs,项目名称:git-remote-dropbox,代码行数:7,代码来源:__init__.py

示例12: main_plugin

def main_plugin():
    '''Main function when invoked as a protoc plugin.'''

    import sys
    if sys.platform == "win32":
        import os, msvcrt
        # Set stdin and stdout to binary mode
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    
    data = sys.stdin.read()
    request = plugin_pb2.CodeGeneratorRequest.FromString(data)
    
    import shlex
    args = shlex.split(request.parameter)
    options, dummy = optparser.parse_args(args)
    
    Globals.verbose_options = options.verbose
    
    response = plugin_pb2.CodeGeneratorResponse()
    
    for filename in request.file_to_generate:
        for fdesc in request.proto_file:
            if fdesc.name == filename:
                results = process_file(filename, fdesc, options)
                
                f = response.file.add()
                f.name = results['headername']
                f.content = results['headerdata']

                f = response.file.add()
                f.name = results['sourcename']
                f.content = results['sourcedata']    
    
    sys.stdout.write(response.SerializeToString())
开发者ID:feshie,项目名称:sensors,代码行数:35,代码来源:nanopb_generator.py

示例13: EncodeAndWriteToStdout

def EncodeAndWriteToStdout(s, encoding='utf-8'):
  """Encode the given string and emit to stdout.

  The string may contain non-ascii characters. This is a problem when stdout is
  redirected, because then Python doesn't know the encoding and we may get a
  UnicodeEncodeError.

  Arguments:
    s: (string) The string to encode.
    encoding: (string) The encoding of the string.
  """
  if PY3:
    sys.stdout.buffer.write(s.encode(encoding))
  elif sys.platform == 'win32':
    # On python 2 and Windows universal newline transformation will be in
    # effect on stdout. Python 2 will not let us avoid the easily because
    # it happens based on whether the file handle is opened in O_BINARY or
    # O_TEXT state. However we can tell Windows itself to change the current
    # mode, and python 2 will follow suit. However we must take care to change
    # the mode on the actual external stdout not just the current sys.stdout
    # which may have been monkey-patched inside the python environment.
    import msvcrt  # pylint: disable=g-import-not-at-top
    if sys.__stdout__ is sys.stdout:
      msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    sys.stdout.write(s.encode(encoding))
  else:
    sys.stdout.write(s.encode(encoding))
开发者ID:boada,项目名称:yapf,代码行数:27,代码来源:py3compat.py

示例14: upload_mode

def upload_mode():
    try:
        import msvcrt
        msvcrt.setmode(0, os.O_BINARY)
        msvcrt.setmode(1, os.O_BINARY)
    except ImportError:
        pass
开发者ID:tukiyo,项目名称:sample,代码行数:7,代码来源:file_upload_func.py

示例15: unhexdump

	def unhexdump(self,infile:str):
		"decode hexdump from file (use '-' for stdin) (warning: outputs binary data)"
		if g.platform == 'win':
			import msvcrt
			msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
		hexdata = get_data_from_file(infile,dash=True,quiet=True)
		return decode_pretty_hexdump(hexdata)
开发者ID:mmgen,项目名称:mmgen,代码行数:7,代码来源:tool.py


注:本文中的msvcrt.setmode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。