##// END OF EJS Templates
py3: byteify strings in pycompat...
Matt Harbison -
r39678:a407f900 default
parent child Browse files
Show More
@@ -1,432 +1,432 b''
1 # pycompat.py - portability shim for python 3
1 # pycompat.py - portability shim for python 3
2 #
2 #
3 # This software may be used and distributed according to the terms of the
3 # This software may be used and distributed according to the terms of the
4 # GNU General Public License version 2 or any later version.
4 # GNU General Public License version 2 or any later version.
5
5
6 """Mercurial portability shim for python 3.
6 """Mercurial portability shim for python 3.
7
7
8 This contains aliases to hide python version-specific details from the core.
8 This contains aliases to hide python version-specific details from the core.
9 """
9 """
10
10
11 from __future__ import absolute_import
11 from __future__ import absolute_import
12
12
13 import getopt
13 import getopt
14 import inspect
14 import inspect
15 import os
15 import os
16 import shlex
16 import shlex
17 import sys
17 import sys
18 import tempfile
18 import tempfile
19
19
20 ispy3 = (sys.version_info[0] >= 3)
20 ispy3 = (sys.version_info[0] >= 3)
21 ispypy = (r'__pypy__' in sys.builtin_module_names)
21 ispypy = (r'__pypy__' in sys.builtin_module_names)
22
22
23 if not ispy3:
23 if not ispy3:
24 import cookielib
24 import cookielib
25 import cPickle as pickle
25 import cPickle as pickle
26 import httplib
26 import httplib
27 import Queue as queue
27 import Queue as queue
28 import SocketServer as socketserver
28 import SocketServer as socketserver
29 import xmlrpclib
29 import xmlrpclib
30
30
31 from .thirdparty.concurrent import futures
31 from .thirdparty.concurrent import futures
32
32
33 def future_set_exception_info(f, exc_info):
33 def future_set_exception_info(f, exc_info):
34 f.set_exception_info(*exc_info)
34 f.set_exception_info(*exc_info)
35 else:
35 else:
36 import concurrent.futures as futures
36 import concurrent.futures as futures
37 import http.cookiejar as cookielib
37 import http.cookiejar as cookielib
38 import http.client as httplib
38 import http.client as httplib
39 import pickle
39 import pickle
40 import queue as queue
40 import queue as queue
41 import socketserver
41 import socketserver
42 import xmlrpc.client as xmlrpclib
42 import xmlrpc.client as xmlrpclib
43
43
44 def future_set_exception_info(f, exc_info):
44 def future_set_exception_info(f, exc_info):
45 f.set_exception(exc_info[0])
45 f.set_exception(exc_info[0])
46
46
47 def identity(a):
47 def identity(a):
48 return a
48 return a
49
49
50 def _rapply(f, xs):
50 def _rapply(f, xs):
51 if xs is None:
51 if xs is None:
52 # assume None means non-value of optional data
52 # assume None means non-value of optional data
53 return xs
53 return xs
54 if isinstance(xs, (list, set, tuple)):
54 if isinstance(xs, (list, set, tuple)):
55 return type(xs)(_rapply(f, x) for x in xs)
55 return type(xs)(_rapply(f, x) for x in xs)
56 if isinstance(xs, dict):
56 if isinstance(xs, dict):
57 return type(xs)((_rapply(f, k), _rapply(f, v)) for k, v in xs.items())
57 return type(xs)((_rapply(f, k), _rapply(f, v)) for k, v in xs.items())
58 return f(xs)
58 return f(xs)
59
59
60 def rapply(f, xs):
60 def rapply(f, xs):
61 """Apply function recursively to every item preserving the data structure
61 """Apply function recursively to every item preserving the data structure
62
62
63 >>> def f(x):
63 >>> def f(x):
64 ... return 'f(%s)' % x
64 ... return 'f(%s)' % x
65 >>> rapply(f, None) is None
65 >>> rapply(f, None) is None
66 True
66 True
67 >>> rapply(f, 'a')
67 >>> rapply(f, 'a')
68 'f(a)'
68 'f(a)'
69 >>> rapply(f, {'a'}) == {'f(a)'}
69 >>> rapply(f, {'a'}) == {'f(a)'}
70 True
70 True
71 >>> rapply(f, ['a', 'b', None, {'c': 'd'}, []])
71 >>> rapply(f, ['a', 'b', None, {'c': 'd'}, []])
72 ['f(a)', 'f(b)', None, {'f(c)': 'f(d)'}, []]
72 ['f(a)', 'f(b)', None, {'f(c)': 'f(d)'}, []]
73
73
74 >>> xs = [object()]
74 >>> xs = [object()]
75 >>> rapply(identity, xs) is xs
75 >>> rapply(identity, xs) is xs
76 True
76 True
77 """
77 """
78 if f is identity:
78 if f is identity:
79 # fast path mainly for py2
79 # fast path mainly for py2
80 return xs
80 return xs
81 return _rapply(f, xs)
81 return _rapply(f, xs)
82
82
83 if ispy3:
83 if ispy3:
84 import builtins
84 import builtins
85 import functools
85 import functools
86 import io
86 import io
87 import struct
87 import struct
88
88
89 fsencode = os.fsencode
89 fsencode = os.fsencode
90 fsdecode = os.fsdecode
90 fsdecode = os.fsdecode
91 oscurdir = os.curdir.encode('ascii')
91 oscurdir = os.curdir.encode('ascii')
92 oslinesep = os.linesep.encode('ascii')
92 oslinesep = os.linesep.encode('ascii')
93 osname = os.name.encode('ascii')
93 osname = os.name.encode('ascii')
94 ospathsep = os.pathsep.encode('ascii')
94 ospathsep = os.pathsep.encode('ascii')
95 ospardir = os.pardir.encode('ascii')
95 ospardir = os.pardir.encode('ascii')
96 ossep = os.sep.encode('ascii')
96 ossep = os.sep.encode('ascii')
97 osaltsep = os.altsep
97 osaltsep = os.altsep
98 if osaltsep:
98 if osaltsep:
99 osaltsep = osaltsep.encode('ascii')
99 osaltsep = osaltsep.encode('ascii')
100 # os.getcwd() on Python 3 returns string, but it has os.getcwdb() which
100 # os.getcwd() on Python 3 returns string, but it has os.getcwdb() which
101 # returns bytes.
101 # returns bytes.
102 getcwd = os.getcwdb
102 getcwd = os.getcwdb
103 sysplatform = sys.platform.encode('ascii')
103 sysplatform = sys.platform.encode('ascii')
104 sysexecutable = sys.executable
104 sysexecutable = sys.executable
105 if sysexecutable:
105 if sysexecutable:
106 sysexecutable = os.fsencode(sysexecutable)
106 sysexecutable = os.fsencode(sysexecutable)
107 bytesio = io.BytesIO
107 bytesio = io.BytesIO
108 # TODO deprecate stringio name, as it is a lie on Python 3.
108 # TODO deprecate stringio name, as it is a lie on Python 3.
109 stringio = bytesio
109 stringio = bytesio
110
110
111 def maplist(*args):
111 def maplist(*args):
112 return list(map(*args))
112 return list(map(*args))
113
113
114 def rangelist(*args):
114 def rangelist(*args):
115 return list(range(*args))
115 return list(range(*args))
116
116
117 def ziplist(*args):
117 def ziplist(*args):
118 return list(zip(*args))
118 return list(zip(*args))
119
119
120 rawinput = input
120 rawinput = input
121 getargspec = inspect.getfullargspec
121 getargspec = inspect.getfullargspec
122
122
123 long = int
123 long = int
124
124
125 # TODO: .buffer might not exist if std streams were replaced; we'll need
125 # TODO: .buffer might not exist if std streams were replaced; we'll need
126 # a silly wrapper to make a bytes stream backed by a unicode one.
126 # a silly wrapper to make a bytes stream backed by a unicode one.
127 stdin = sys.stdin.buffer
127 stdin = sys.stdin.buffer
128 stdout = sys.stdout.buffer
128 stdout = sys.stdout.buffer
129 stderr = sys.stderr.buffer
129 stderr = sys.stderr.buffer
130
130
131 # Since Python 3 converts argv to wchar_t type by Py_DecodeLocale() on Unix,
131 # Since Python 3 converts argv to wchar_t type by Py_DecodeLocale() on Unix,
132 # we can use os.fsencode() to get back bytes argv.
132 # we can use os.fsencode() to get back bytes argv.
133 #
133 #
134 # https://hg.python.org/cpython/file/v3.5.1/Programs/python.c#l55
134 # https://hg.python.org/cpython/file/v3.5.1/Programs/python.c#l55
135 #
135 #
136 # TODO: On Windows, the native argv is wchar_t, so we'll need a different
136 # TODO: On Windows, the native argv is wchar_t, so we'll need a different
137 # workaround to simulate the Python 2 (i.e. ANSI Win32 API) behavior.
137 # workaround to simulate the Python 2 (i.e. ANSI Win32 API) behavior.
138 if getattr(sys, 'argv', None) is not None:
138 if getattr(sys, 'argv', None) is not None:
139 sysargv = list(map(os.fsencode, sys.argv))
139 sysargv = list(map(os.fsencode, sys.argv))
140
140
141 bytechr = struct.Struct('>B').pack
141 bytechr = struct.Struct(r'>B').pack
142 byterepr = b'%r'.__mod__
142 byterepr = b'%r'.__mod__
143
143
144 class bytestr(bytes):
144 class bytestr(bytes):
145 """A bytes which mostly acts as a Python 2 str
145 """A bytes which mostly acts as a Python 2 str
146
146
147 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
147 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
148 ('', 'foo', 'ascii', '1')
148 ('', 'foo', 'ascii', '1')
149 >>> s = bytestr(b'foo')
149 >>> s = bytestr(b'foo')
150 >>> assert s is bytestr(s)
150 >>> assert s is bytestr(s)
151
151
152 __bytes__() should be called if provided:
152 __bytes__() should be called if provided:
153
153
154 >>> class bytesable(object):
154 >>> class bytesable(object):
155 ... def __bytes__(self):
155 ... def __bytes__(self):
156 ... return b'bytes'
156 ... return b'bytes'
157 >>> bytestr(bytesable())
157 >>> bytestr(bytesable())
158 'bytes'
158 'bytes'
159
159
160 There's no implicit conversion from non-ascii str as its encoding is
160 There's no implicit conversion from non-ascii str as its encoding is
161 unknown:
161 unknown:
162
162
163 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
163 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
164 Traceback (most recent call last):
164 Traceback (most recent call last):
165 ...
165 ...
166 UnicodeEncodeError: ...
166 UnicodeEncodeError: ...
167
167
168 Comparison between bytestr and bytes should work:
168 Comparison between bytestr and bytes should work:
169
169
170 >>> assert bytestr(b'foo') == b'foo'
170 >>> assert bytestr(b'foo') == b'foo'
171 >>> assert b'foo' == bytestr(b'foo')
171 >>> assert b'foo' == bytestr(b'foo')
172 >>> assert b'f' in bytestr(b'foo')
172 >>> assert b'f' in bytestr(b'foo')
173 >>> assert bytestr(b'f') in b'foo'
173 >>> assert bytestr(b'f') in b'foo'
174
174
175 Sliced elements should be bytes, not integer:
175 Sliced elements should be bytes, not integer:
176
176
177 >>> s[1], s[:2]
177 >>> s[1], s[:2]
178 (b'o', b'fo')
178 (b'o', b'fo')
179 >>> list(s), list(reversed(s))
179 >>> list(s), list(reversed(s))
180 ([b'f', b'o', b'o'], [b'o', b'o', b'f'])
180 ([b'f', b'o', b'o'], [b'o', b'o', b'f'])
181
181
182 As bytestr type isn't propagated across operations, you need to cast
182 As bytestr type isn't propagated across operations, you need to cast
183 bytes to bytestr explicitly:
183 bytes to bytestr explicitly:
184
184
185 >>> s = bytestr(b'foo').upper()
185 >>> s = bytestr(b'foo').upper()
186 >>> t = bytestr(s)
186 >>> t = bytestr(s)
187 >>> s[0], t[0]
187 >>> s[0], t[0]
188 (70, b'F')
188 (70, b'F')
189
189
190 Be careful to not pass a bytestr object to a function which expects
190 Be careful to not pass a bytestr object to a function which expects
191 bytearray-like behavior.
191 bytearray-like behavior.
192
192
193 >>> t = bytes(t) # cast to bytes
193 >>> t = bytes(t) # cast to bytes
194 >>> assert type(t) is bytes
194 >>> assert type(t) is bytes
195 """
195 """
196
196
197 def __new__(cls, s=b''):
197 def __new__(cls, s=b''):
198 if isinstance(s, bytestr):
198 if isinstance(s, bytestr):
199 return s
199 return s
200 if (not isinstance(s, (bytes, bytearray))
200 if (not isinstance(s, (bytes, bytearray))
201 and not hasattr(s, u'__bytes__')): # hasattr-py3-only
201 and not hasattr(s, u'__bytes__')): # hasattr-py3-only
202 s = str(s).encode(u'ascii')
202 s = str(s).encode(u'ascii')
203 return bytes.__new__(cls, s)
203 return bytes.__new__(cls, s)
204
204
205 def __getitem__(self, key):
205 def __getitem__(self, key):
206 s = bytes.__getitem__(self, key)
206 s = bytes.__getitem__(self, key)
207 if not isinstance(s, bytes):
207 if not isinstance(s, bytes):
208 s = bytechr(s)
208 s = bytechr(s)
209 return s
209 return s
210
210
211 def __iter__(self):
211 def __iter__(self):
212 return iterbytestr(bytes.__iter__(self))
212 return iterbytestr(bytes.__iter__(self))
213
213
214 def __repr__(self):
214 def __repr__(self):
215 return bytes.__repr__(self)[1:] # drop b''
215 return bytes.__repr__(self)[1:] # drop b''
216
216
217 def iterbytestr(s):
217 def iterbytestr(s):
218 """Iterate bytes as if it were a str object of Python 2"""
218 """Iterate bytes as if it were a str object of Python 2"""
219 return map(bytechr, s)
219 return map(bytechr, s)
220
220
221 def maybebytestr(s):
221 def maybebytestr(s):
222 """Promote bytes to bytestr"""
222 """Promote bytes to bytestr"""
223 if isinstance(s, bytes):
223 if isinstance(s, bytes):
224 return bytestr(s)
224 return bytestr(s)
225 return s
225 return s
226
226
227 def sysbytes(s):
227 def sysbytes(s):
228 """Convert an internal str (e.g. keyword, __doc__) back to bytes
228 """Convert an internal str (e.g. keyword, __doc__) back to bytes
229
229
230 This never raises UnicodeEncodeError, but only ASCII characters
230 This never raises UnicodeEncodeError, but only ASCII characters
231 can be round-trip by sysstr(sysbytes(s)).
231 can be round-trip by sysstr(sysbytes(s)).
232 """
232 """
233 return s.encode(u'utf-8')
233 return s.encode(u'utf-8')
234
234
235 def sysstr(s):
235 def sysstr(s):
236 """Return a keyword str to be passed to Python functions such as
236 """Return a keyword str to be passed to Python functions such as
237 getattr() and str.encode()
237 getattr() and str.encode()
238
238
239 This never raises UnicodeDecodeError. Non-ascii characters are
239 This never raises UnicodeDecodeError. Non-ascii characters are
240 considered invalid and mapped to arbitrary but unique code points
240 considered invalid and mapped to arbitrary but unique code points
241 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
241 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
242 """
242 """
243 if isinstance(s, builtins.str):
243 if isinstance(s, builtins.str):
244 return s
244 return s
245 return s.decode(u'latin-1')
245 return s.decode(u'latin-1')
246
246
247 def strurl(url):
247 def strurl(url):
248 """Converts a bytes url back to str"""
248 """Converts a bytes url back to str"""
249 if isinstance(url, bytes):
249 if isinstance(url, bytes):
250 return url.decode(u'ascii')
250 return url.decode(u'ascii')
251 return url
251 return url
252
252
253 def bytesurl(url):
253 def bytesurl(url):
254 """Converts a str url to bytes by encoding in ascii"""
254 """Converts a str url to bytes by encoding in ascii"""
255 if isinstance(url, str):
255 if isinstance(url, str):
256 return url.encode(u'ascii')
256 return url.encode(u'ascii')
257 return url
257 return url
258
258
259 def raisewithtb(exc, tb):
259 def raisewithtb(exc, tb):
260 """Raise exception with the given traceback"""
260 """Raise exception with the given traceback"""
261 raise exc.with_traceback(tb)
261 raise exc.with_traceback(tb)
262
262
263 def getdoc(obj):
263 def getdoc(obj):
264 """Get docstring as bytes; may be None so gettext() won't confuse it
264 """Get docstring as bytes; may be None so gettext() won't confuse it
265 with _('')"""
265 with _('')"""
266 doc = getattr(obj, u'__doc__', None)
266 doc = getattr(obj, u'__doc__', None)
267 if doc is None:
267 if doc is None:
268 return doc
268 return doc
269 return sysbytes(doc)
269 return sysbytes(doc)
270
270
271 def _wrapattrfunc(f):
271 def _wrapattrfunc(f):
272 @functools.wraps(f)
272 @functools.wraps(f)
273 def w(object, name, *args):
273 def w(object, name, *args):
274 return f(object, sysstr(name), *args)
274 return f(object, sysstr(name), *args)
275 return w
275 return w
276
276
277 # these wrappers are automagically imported by hgloader
277 # these wrappers are automagically imported by hgloader
278 delattr = _wrapattrfunc(builtins.delattr)
278 delattr = _wrapattrfunc(builtins.delattr)
279 getattr = _wrapattrfunc(builtins.getattr)
279 getattr = _wrapattrfunc(builtins.getattr)
280 hasattr = _wrapattrfunc(builtins.hasattr)
280 hasattr = _wrapattrfunc(builtins.hasattr)
281 setattr = _wrapattrfunc(builtins.setattr)
281 setattr = _wrapattrfunc(builtins.setattr)
282 xrange = builtins.range
282 xrange = builtins.range
283 unicode = str
283 unicode = str
284
284
285 def open(name, mode='r', buffering=-1, encoding=None):
285 def open(name, mode=b'r', buffering=-1, encoding=None):
286 return builtins.open(name, sysstr(mode), buffering, encoding)
286 return builtins.open(name, sysstr(mode), buffering, encoding)
287
287
288 safehasattr = _wrapattrfunc(builtins.hasattr)
288 safehasattr = _wrapattrfunc(builtins.hasattr)
289
289
290 def _getoptbwrapper(orig, args, shortlist, namelist):
290 def _getoptbwrapper(orig, args, shortlist, namelist):
291 """
291 """
292 Takes bytes arguments, converts them to unicode, pass them to
292 Takes bytes arguments, converts them to unicode, pass them to
293 getopt.getopt(), convert the returned values back to bytes and then
293 getopt.getopt(), convert the returned values back to bytes and then
294 return them for Python 3 compatibility as getopt.getopt() don't accepts
294 return them for Python 3 compatibility as getopt.getopt() don't accepts
295 bytes on Python 3.
295 bytes on Python 3.
296 """
296 """
297 args = [a.decode('latin-1') for a in args]
297 args = [a.decode('latin-1') for a in args]
298 shortlist = shortlist.decode('latin-1')
298 shortlist = shortlist.decode('latin-1')
299 namelist = [a.decode('latin-1') for a in namelist]
299 namelist = [a.decode('latin-1') for a in namelist]
300 opts, args = orig(args, shortlist, namelist)
300 opts, args = orig(args, shortlist, namelist)
301 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
301 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
302 for a in opts]
302 for a in opts]
303 args = [a.encode('latin-1') for a in args]
303 args = [a.encode('latin-1') for a in args]
304 return opts, args
304 return opts, args
305
305
306 def strkwargs(dic):
306 def strkwargs(dic):
307 """
307 """
308 Converts the keys of a python dictonary to str i.e. unicodes so that
308 Converts the keys of a python dictonary to str i.e. unicodes so that
309 they can be passed as keyword arguments as dictonaries with bytes keys
309 they can be passed as keyword arguments as dictonaries with bytes keys
310 can't be passed as keyword arguments to functions on Python 3.
310 can't be passed as keyword arguments to functions on Python 3.
311 """
311 """
312 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
312 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
313 return dic
313 return dic
314
314
315 def byteskwargs(dic):
315 def byteskwargs(dic):
316 """
316 """
317 Converts keys of python dictonaries to bytes as they were converted to
317 Converts keys of python dictonaries to bytes as they were converted to
318 str to pass that dictonary as a keyword argument on Python 3.
318 str to pass that dictonary as a keyword argument on Python 3.
319 """
319 """
320 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
320 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
321 return dic
321 return dic
322
322
323 # TODO: handle shlex.shlex().
323 # TODO: handle shlex.shlex().
324 def shlexsplit(s, comments=False, posix=True):
324 def shlexsplit(s, comments=False, posix=True):
325 """
325 """
326 Takes bytes argument, convert it to str i.e. unicodes, pass that into
326 Takes bytes argument, convert it to str i.e. unicodes, pass that into
327 shlex.split(), convert the returned value to bytes and return that for
327 shlex.split(), convert the returned value to bytes and return that for
328 Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
328 Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
329 """
329 """
330 ret = shlex.split(s.decode('latin-1'), comments, posix)
330 ret = shlex.split(s.decode('latin-1'), comments, posix)
331 return [a.encode('latin-1') for a in ret]
331 return [a.encode('latin-1') for a in ret]
332
332
333 else:
333 else:
334 import cStringIO
334 import cStringIO
335
335
336 xrange = xrange
336 xrange = xrange
337 unicode = unicode
337 unicode = unicode
338 bytechr = chr
338 bytechr = chr
339 byterepr = repr
339 byterepr = repr
340 bytestr = str
340 bytestr = str
341 iterbytestr = iter
341 iterbytestr = iter
342 maybebytestr = identity
342 maybebytestr = identity
343 sysbytes = identity
343 sysbytes = identity
344 sysstr = identity
344 sysstr = identity
345 strurl = identity
345 strurl = identity
346 bytesurl = identity
346 bytesurl = identity
347
347
348 # this can't be parsed on Python 3
348 # this can't be parsed on Python 3
349 exec('def raisewithtb(exc, tb):\n'
349 exec('def raisewithtb(exc, tb):\n'
350 ' raise exc, None, tb\n')
350 ' raise exc, None, tb\n')
351
351
352 def fsencode(filename):
352 def fsencode(filename):
353 """
353 """
354 Partial backport from os.py in Python 3, which only accepts bytes.
354 Partial backport from os.py in Python 3, which only accepts bytes.
355 In Python 2, our paths should only ever be bytes, a unicode path
355 In Python 2, our paths should only ever be bytes, a unicode path
356 indicates a bug.
356 indicates a bug.
357 """
357 """
358 if isinstance(filename, str):
358 if isinstance(filename, str):
359 return filename
359 return filename
360 else:
360 else:
361 raise TypeError(
361 raise TypeError(
362 "expect str, not %s" % type(filename).__name__)
362 r"expect str, not %s" % type(filename).__name__)
363
363
364 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
364 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
365 # better not to touch Python 2 part as it's already working fine.
365 # better not to touch Python 2 part as it's already working fine.
366 fsdecode = identity
366 fsdecode = identity
367
367
368 def getdoc(obj):
368 def getdoc(obj):
369 return getattr(obj, '__doc__', None)
369 return getattr(obj, '__doc__', None)
370
370
371 _notset = object()
371 _notset = object()
372
372
373 def safehasattr(thing, attr):
373 def safehasattr(thing, attr):
374 return getattr(thing, attr, _notset) is not _notset
374 return getattr(thing, attr, _notset) is not _notset
375
375
376 def _getoptbwrapper(orig, args, shortlist, namelist):
376 def _getoptbwrapper(orig, args, shortlist, namelist):
377 return orig(args, shortlist, namelist)
377 return orig(args, shortlist, namelist)
378
378
379 strkwargs = identity
379 strkwargs = identity
380 byteskwargs = identity
380 byteskwargs = identity
381
381
382 oscurdir = os.curdir
382 oscurdir = os.curdir
383 oslinesep = os.linesep
383 oslinesep = os.linesep
384 osname = os.name
384 osname = os.name
385 ospathsep = os.pathsep
385 ospathsep = os.pathsep
386 ospardir = os.pardir
386 ospardir = os.pardir
387 ossep = os.sep
387 ossep = os.sep
388 osaltsep = os.altsep
388 osaltsep = os.altsep
389 long = long
389 long = long
390 stdin = sys.stdin
390 stdin = sys.stdin
391 stdout = sys.stdout
391 stdout = sys.stdout
392 stderr = sys.stderr
392 stderr = sys.stderr
393 if getattr(sys, 'argv', None) is not None:
393 if getattr(sys, 'argv', None) is not None:
394 sysargv = sys.argv
394 sysargv = sys.argv
395 sysplatform = sys.platform
395 sysplatform = sys.platform
396 getcwd = os.getcwd
396 getcwd = os.getcwd
397 sysexecutable = sys.executable
397 sysexecutable = sys.executable
398 shlexsplit = shlex.split
398 shlexsplit = shlex.split
399 bytesio = cStringIO.StringIO
399 bytesio = cStringIO.StringIO
400 stringio = bytesio
400 stringio = bytesio
401 maplist = map
401 maplist = map
402 rangelist = range
402 rangelist = range
403 ziplist = zip
403 ziplist = zip
404 rawinput = raw_input
404 rawinput = raw_input
405 getargspec = inspect.getargspec
405 getargspec = inspect.getargspec
406
406
407 isjython = sysplatform.startswith('java')
407 isjython = sysplatform.startswith(b'java')
408
408
409 isdarwin = sysplatform == 'darwin'
409 isdarwin = sysplatform == b'darwin'
410 isposix = osname == 'posix'
410 isposix = osname == b'posix'
411 iswindows = osname == 'nt'
411 iswindows = osname == b'nt'
412
412
413 def getoptb(args, shortlist, namelist):
413 def getoptb(args, shortlist, namelist):
414 return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
414 return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
415
415
416 def gnugetoptb(args, shortlist, namelist):
416 def gnugetoptb(args, shortlist, namelist):
417 return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
417 return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
418
418
419 def mkdtemp(suffix=b'', prefix=b'tmp', dir=None):
419 def mkdtemp(suffix=b'', prefix=b'tmp', dir=None):
420 return tempfile.mkdtemp(suffix, prefix, dir)
420 return tempfile.mkdtemp(suffix, prefix, dir)
421
421
422 # text=True is not supported; use util.from/tonativeeol() instead
422 # text=True is not supported; use util.from/tonativeeol() instead
423 def mkstemp(suffix=b'', prefix=b'tmp', dir=None):
423 def mkstemp(suffix=b'', prefix=b'tmp', dir=None):
424 return tempfile.mkstemp(suffix, prefix, dir)
424 return tempfile.mkstemp(suffix, prefix, dir)
425
425
426 # mode must include 'b'ytes as encoding= is not supported
426 # mode must include 'b'ytes as encoding= is not supported
427 def namedtempfile(mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None,
427 def namedtempfile(mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None,
428 delete=True):
428 delete=True):
429 mode = sysstr(mode)
429 mode = sysstr(mode)
430 assert r'b' in mode
430 assert r'b' in mode
431 return tempfile.NamedTemporaryFile(mode, bufsize, suffix=suffix,
431 return tempfile.NamedTemporaryFile(mode, bufsize, suffix=suffix,
432 prefix=prefix, dir=dir, delete=delete)
432 prefix=prefix, dir=dir, delete=delete)
General Comments 0
You need to be logged in to leave comments. Login now