本文整理汇总了Python中msvcrt.setmode函数的典型用法代码示例。如果您正苦于以下问题:Python setmode函数的具体用法?Python setmode怎么用?Python setmode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了setmode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: enviarStout
def enviarStout(rutaarchivo):
ruta,nombre=os.path.split(rutaarchivo)
ruta,temp=os.path.split(registro.LeerReg("Trabajo"))
ruta+="\\"+temp+"\\stdout\\"
# sys.stdout.write(nombre + "\n" + ruta + "\n\n")
if not os.path.isfile(os.path.join(ruta,nombre)):
sys.stdout.write("Error No existe archivo:"+nombre)
GuardarLog ("Error No exite stdout")
sys.exit(0)
return 0
try:
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
arch=open(os.path.join(ruta,nombre),"rb",0)
sys.stdout.write(arch.read())
#print(datos)
#datos=arch.read(1))
#while len(datos)>0:
# sys.stdout.write(datos)
# datos=arch.read(1)
except:
sys.stdout.write("error")
GuardarLog ("Error: lecutra:" + ruta+nombre)
finally:
arch.close()
开发者ID:calimacaco,项目名称:pyfacil,代码行数:27,代码来源:captura2.py
示例17: _build_lint_target
def _build_lint_target(path, config_dict): # type: (Path, Dict[str, Any]) -> AbstractLintTarget
if path == _stdin_symbol:
stdin_alt_path = get_config_value(config_dict, ['cmdargs', 'stdin_display_name'])
# NOTE: In Python 3, sys.stdin is a string not bytes. Then we can get bytes by sys.stdin.buffer.
# But in Python 2, sys.stdin.buffer is not defined. But we can get bytes by sys.stdin directly.
is_python_3 = hasattr(sys.stdin, 'buffer')
if is_python_3:
lint_target = LintTargetBufferedStream(
alternate_path=Path(stdin_alt_path),
buffered_io=sys.stdin.buffer
)
else:
# NOTE: Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
# SEE: https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin/38939320#38939320
if sys.platform == 'win32':
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
lint_target = LintTargetBufferedStream(
alternate_path=Path(stdin_alt_path),
buffered_io=sys.stdin
)
return CachedLintTarget(lint_target)
else:
lint_target = LintTargetFile(path)
return CachedLintTarget(lint_target)
开发者ID:Kuniwak,项目名称:vint,代码行数:31,代码来源:cli.py
示例18: main
def main(argv):
if len(argv) < 3:
print __doc__
sys.exit(-1)
if sys.platform == "win32":
import msvcrt, os
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
# 01/13/05 note: my experience is you cannot pipe UTF16 output from a shell
# to a file even with os.O_BINARY setting. Must write to file directly.
option = argv[1]
filename = argv[2]
fp = file(filename,'rb')
if option == '-d':
meta = {}
result = test_distill(fp, sys.stdout, meta)
print >>sys.stderr
print >>sys.stderr, '-'*72
print >>sys.stderr, 'Meta:',
pprint.pprint(meta, sys.stderr)
print >>sys.stderr, 'Result:', result
else:
print __doc__
sys.exit(-1)
fp.close()
开发者ID:BackupTheBerlios,项目名称:mindretrieve-svn,代码行数:28,代码来源:distillML.py
示例19: _set_data_field
def _set_data_field(fields, args):
if 'location' not in fields and 'copy_from' not in fields:
if args.file:
fields['data'] = open(args.file, 'rb')
else:
# distinguish cases where:
# (1) stdin is not valid (as in cron jobs):
# glance ... <&-
# (2) image data is provided through standard input:
# glance ... < /tmp/file or cat /tmp/file | glance ...
# (3) no image data provided:
# glance ...
try:
os.fstat(0)
except OSError:
# (1) stdin is not valid (closed...)
fields['data'] = None
return
if not sys.stdin.isatty():
# (2) image data is provided through standard input
if msvcrt:
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
fields['data'] = sys.stdin
else:
# (3) no image data provided
fields['data'] = None
开发者ID:CiscoAS,项目名称:python-glanceclient,代码行数:26,代码来源:shell.py
示例20: main
def main(args=sys.argv[1:]):
parser = optparse.OptionParser(usage=__doc__.strip())
parser.add_option(
"--factory", help="Full python path to the image factory class to "
"create the image with. You can use the following shortcuts to the "
"built-in image factory classes: {0}.".format(
", ".join(sorted(default_factories.keys()))))
parser.add_option(
"--optimize", type=int, help="Optimize the data by looking for chunks "
"of at least this many characters that could use a more efficient "
"encoding method. Use 0 to turn off chunk optimization.")
parser.add_option(
"--error-correction", type='choice',
choices=sorted(error_correction.keys()), default='M',
help="The error correction level to use. Choices are L (7%), "
"M (15%, default), Q (25%), and H (30%).")
opts, args = parser.parse_args(args)
qr = qrcode.QRCode(
error_correction=error_correction[opts.error_correction])
if opts.factory:
module = default_factories.get(opts.factory, opts.factory)
if '.' not in module:
parser.error("The image factory is not a full python path")
module, name = module.rsplit('.', 1)
imp = __import__(module, {}, [], [name])
image_factory = getattr(imp, name)
else:
image_factory = None
if args:
data = args[0]
else:
# Use sys.stdin.buffer if available (Python 3) avoiding
# UnicodeDecodeErrors.
stdin_buffer = getattr(sys.stdin, 'buffer', sys.stdin)
data = stdin_buffer.read()
if opts.optimize is None:
qr.add_data(data)
else:
qr.add_data(data, optimize=opts.optimize)
if image_factory is None and os.isatty(sys.stdout.fileno()):
qr.print_ascii(tty=True)
return
img = qr.make_image(image_factory=image_factory)
sys.stdout.flush()
# Use sys.stdout.buffer if available (Python 3), avoiding
# UnicodeDecodeErrors.
stdout_buffer = getattr(sys.stdout, 'buffer', None)
if not stdout_buffer:
if sys.platform == 'win32': # pragma: no cover
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
stdout_buffer = sys.stdout
img.save(stdout_buffer)
开发者ID:0x5e,项目名称:python-qrcode,代码行数:60,代码来源:console_scripts.py
注:本文中的msvcrt.setmode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论