本文整理汇总了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()
示例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)
示例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))
示例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)
示例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()
示例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()
示例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'
示例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
示例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
示例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)
示例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)
示例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())
示例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))
示例14: upload_mode
def upload_mode():
try:
import msvcrt
msvcrt.setmode(0, os.O_BINARY)
msvcrt.setmode(1, os.O_BINARY)
except ImportError:
pass
示例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)