##// END OF EJS Templates
pycompat: add xrange alias for Python 2...
Gregory Szorc -
r38805:7eba8f83 default
parent child Browse files
Show More
@@ -1,428 +1,429 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 # TODO: .buffer might not exist if std streams were replaced; we'll need
123 # TODO: .buffer might not exist if std streams were replaced; we'll need
124 # a silly wrapper to make a bytes stream backed by a unicode one.
124 # a silly wrapper to make a bytes stream backed by a unicode one.
125 stdin = sys.stdin.buffer
125 stdin = sys.stdin.buffer
126 stdout = sys.stdout.buffer
126 stdout = sys.stdout.buffer
127 stderr = sys.stderr.buffer
127 stderr = sys.stderr.buffer
128
128
129 # Since Python 3 converts argv to wchar_t type by Py_DecodeLocale() on Unix,
129 # Since Python 3 converts argv to wchar_t type by Py_DecodeLocale() on Unix,
130 # we can use os.fsencode() to get back bytes argv.
130 # we can use os.fsencode() to get back bytes argv.
131 #
131 #
132 # https://hg.python.org/cpython/file/v3.5.1/Programs/python.c#l55
132 # https://hg.python.org/cpython/file/v3.5.1/Programs/python.c#l55
133 #
133 #
134 # TODO: On Windows, the native argv is wchar_t, so we'll need a different
134 # TODO: On Windows, the native argv is wchar_t, so we'll need a different
135 # workaround to simulate the Python 2 (i.e. ANSI Win32 API) behavior.
135 # workaround to simulate the Python 2 (i.e. ANSI Win32 API) behavior.
136 if getattr(sys, 'argv', None) is not None:
136 if getattr(sys, 'argv', None) is not None:
137 sysargv = list(map(os.fsencode, sys.argv))
137 sysargv = list(map(os.fsencode, sys.argv))
138
138
139 bytechr = struct.Struct('>B').pack
139 bytechr = struct.Struct('>B').pack
140 byterepr = b'%r'.__mod__
140 byterepr = b'%r'.__mod__
141
141
142 class bytestr(bytes):
142 class bytestr(bytes):
143 """A bytes which mostly acts as a Python 2 str
143 """A bytes which mostly acts as a Python 2 str
144
144
145 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
145 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
146 ('', 'foo', 'ascii', '1')
146 ('', 'foo', 'ascii', '1')
147 >>> s = bytestr(b'foo')
147 >>> s = bytestr(b'foo')
148 >>> assert s is bytestr(s)
148 >>> assert s is bytestr(s)
149
149
150 __bytes__() should be called if provided:
150 __bytes__() should be called if provided:
151
151
152 >>> class bytesable(object):
152 >>> class bytesable(object):
153 ... def __bytes__(self):
153 ... def __bytes__(self):
154 ... return b'bytes'
154 ... return b'bytes'
155 >>> bytestr(bytesable())
155 >>> bytestr(bytesable())
156 'bytes'
156 'bytes'
157
157
158 There's no implicit conversion from non-ascii str as its encoding is
158 There's no implicit conversion from non-ascii str as its encoding is
159 unknown:
159 unknown:
160
160
161 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
161 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
162 Traceback (most recent call last):
162 Traceback (most recent call last):
163 ...
163 ...
164 UnicodeEncodeError: ...
164 UnicodeEncodeError: ...
165
165
166 Comparison between bytestr and bytes should work:
166 Comparison between bytestr and bytes should work:
167
167
168 >>> assert bytestr(b'foo') == b'foo'
168 >>> assert bytestr(b'foo') == b'foo'
169 >>> assert b'foo' == bytestr(b'foo')
169 >>> assert b'foo' == bytestr(b'foo')
170 >>> assert b'f' in bytestr(b'foo')
170 >>> assert b'f' in bytestr(b'foo')
171 >>> assert bytestr(b'f') in b'foo'
171 >>> assert bytestr(b'f') in b'foo'
172
172
173 Sliced elements should be bytes, not integer:
173 Sliced elements should be bytes, not integer:
174
174
175 >>> s[1], s[:2]
175 >>> s[1], s[:2]
176 (b'o', b'fo')
176 (b'o', b'fo')
177 >>> list(s), list(reversed(s))
177 >>> list(s), list(reversed(s))
178 ([b'f', b'o', b'o'], [b'o', b'o', b'f'])
178 ([b'f', b'o', b'o'], [b'o', b'o', b'f'])
179
179
180 As bytestr type isn't propagated across operations, you need to cast
180 As bytestr type isn't propagated across operations, you need to cast
181 bytes to bytestr explicitly:
181 bytes to bytestr explicitly:
182
182
183 >>> s = bytestr(b'foo').upper()
183 >>> s = bytestr(b'foo').upper()
184 >>> t = bytestr(s)
184 >>> t = bytestr(s)
185 >>> s[0], t[0]
185 >>> s[0], t[0]
186 (70, b'F')
186 (70, b'F')
187
187
188 Be careful to not pass a bytestr object to a function which expects
188 Be careful to not pass a bytestr object to a function which expects
189 bytearray-like behavior.
189 bytearray-like behavior.
190
190
191 >>> t = bytes(t) # cast to bytes
191 >>> t = bytes(t) # cast to bytes
192 >>> assert type(t) is bytes
192 >>> assert type(t) is bytes
193 """
193 """
194
194
195 def __new__(cls, s=b''):
195 def __new__(cls, s=b''):
196 if isinstance(s, bytestr):
196 if isinstance(s, bytestr):
197 return s
197 return s
198 if (not isinstance(s, (bytes, bytearray))
198 if (not isinstance(s, (bytes, bytearray))
199 and not hasattr(s, u'__bytes__')): # hasattr-py3-only
199 and not hasattr(s, u'__bytes__')): # hasattr-py3-only
200 s = str(s).encode(u'ascii')
200 s = str(s).encode(u'ascii')
201 return bytes.__new__(cls, s)
201 return bytes.__new__(cls, s)
202
202
203 def __getitem__(self, key):
203 def __getitem__(self, key):
204 s = bytes.__getitem__(self, key)
204 s = bytes.__getitem__(self, key)
205 if not isinstance(s, bytes):
205 if not isinstance(s, bytes):
206 s = bytechr(s)
206 s = bytechr(s)
207 return s
207 return s
208
208
209 def __iter__(self):
209 def __iter__(self):
210 return iterbytestr(bytes.__iter__(self))
210 return iterbytestr(bytes.__iter__(self))
211
211
212 def __repr__(self):
212 def __repr__(self):
213 return bytes.__repr__(self)[1:] # drop b''
213 return bytes.__repr__(self)[1:] # drop b''
214
214
215 def iterbytestr(s):
215 def iterbytestr(s):
216 """Iterate bytes as if it were a str object of Python 2"""
216 """Iterate bytes as if it were a str object of Python 2"""
217 return map(bytechr, s)
217 return map(bytechr, s)
218
218
219 def maybebytestr(s):
219 def maybebytestr(s):
220 """Promote bytes to bytestr"""
220 """Promote bytes to bytestr"""
221 if isinstance(s, bytes):
221 if isinstance(s, bytes):
222 return bytestr(s)
222 return bytestr(s)
223 return s
223 return s
224
224
225 def sysbytes(s):
225 def sysbytes(s):
226 """Convert an internal str (e.g. keyword, __doc__) back to bytes
226 """Convert an internal str (e.g. keyword, __doc__) back to bytes
227
227
228 This never raises UnicodeEncodeError, but only ASCII characters
228 This never raises UnicodeEncodeError, but only ASCII characters
229 can be round-trip by sysstr(sysbytes(s)).
229 can be round-trip by sysstr(sysbytes(s)).
230 """
230 """
231 return s.encode(u'utf-8')
231 return s.encode(u'utf-8')
232
232
233 def sysstr(s):
233 def sysstr(s):
234 """Return a keyword str to be passed to Python functions such as
234 """Return a keyword str to be passed to Python functions such as
235 getattr() and str.encode()
235 getattr() and str.encode()
236
236
237 This never raises UnicodeDecodeError. Non-ascii characters are
237 This never raises UnicodeDecodeError. Non-ascii characters are
238 considered invalid and mapped to arbitrary but unique code points
238 considered invalid and mapped to arbitrary but unique code points
239 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
239 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
240 """
240 """
241 if isinstance(s, builtins.str):
241 if isinstance(s, builtins.str):
242 return s
242 return s
243 return s.decode(u'latin-1')
243 return s.decode(u'latin-1')
244
244
245 def strurl(url):
245 def strurl(url):
246 """Converts a bytes url back to str"""
246 """Converts a bytes url back to str"""
247 if isinstance(url, bytes):
247 if isinstance(url, bytes):
248 return url.decode(u'ascii')
248 return url.decode(u'ascii')
249 return url
249 return url
250
250
251 def bytesurl(url):
251 def bytesurl(url):
252 """Converts a str url to bytes by encoding in ascii"""
252 """Converts a str url to bytes by encoding in ascii"""
253 if isinstance(url, str):
253 if isinstance(url, str):
254 return url.encode(u'ascii')
254 return url.encode(u'ascii')
255 return url
255 return url
256
256
257 def raisewithtb(exc, tb):
257 def raisewithtb(exc, tb):
258 """Raise exception with the given traceback"""
258 """Raise exception with the given traceback"""
259 raise exc.with_traceback(tb)
259 raise exc.with_traceback(tb)
260
260
261 def getdoc(obj):
261 def getdoc(obj):
262 """Get docstring as bytes; may be None so gettext() won't confuse it
262 """Get docstring as bytes; may be None so gettext() won't confuse it
263 with _('')"""
263 with _('')"""
264 doc = getattr(obj, u'__doc__', None)
264 doc = getattr(obj, u'__doc__', None)
265 if doc is None:
265 if doc is None:
266 return doc
266 return doc
267 return sysbytes(doc)
267 return sysbytes(doc)
268
268
269 def _wrapattrfunc(f):
269 def _wrapattrfunc(f):
270 @functools.wraps(f)
270 @functools.wraps(f)
271 def w(object, name, *args):
271 def w(object, name, *args):
272 return f(object, sysstr(name), *args)
272 return f(object, sysstr(name), *args)
273 return w
273 return w
274
274
275 # these wrappers are automagically imported by hgloader
275 # these wrappers are automagically imported by hgloader
276 delattr = _wrapattrfunc(builtins.delattr)
276 delattr = _wrapattrfunc(builtins.delattr)
277 getattr = _wrapattrfunc(builtins.getattr)
277 getattr = _wrapattrfunc(builtins.getattr)
278 hasattr = _wrapattrfunc(builtins.hasattr)
278 hasattr = _wrapattrfunc(builtins.hasattr)
279 setattr = _wrapattrfunc(builtins.setattr)
279 setattr = _wrapattrfunc(builtins.setattr)
280 xrange = builtins.range
280 xrange = builtins.range
281 unicode = str
281 unicode = str
282
282
283 def open(name, mode='r', buffering=-1, encoding=None):
283 def open(name, mode='r', buffering=-1, encoding=None):
284 return builtins.open(name, sysstr(mode), buffering, encoding)
284 return builtins.open(name, sysstr(mode), buffering, encoding)
285
285
286 safehasattr = _wrapattrfunc(builtins.hasattr)
286 safehasattr = _wrapattrfunc(builtins.hasattr)
287
287
288 def _getoptbwrapper(orig, args, shortlist, namelist):
288 def _getoptbwrapper(orig, args, shortlist, namelist):
289 """
289 """
290 Takes bytes arguments, converts them to unicode, pass them to
290 Takes bytes arguments, converts them to unicode, pass them to
291 getopt.getopt(), convert the returned values back to bytes and then
291 getopt.getopt(), convert the returned values back to bytes and then
292 return them for Python 3 compatibility as getopt.getopt() don't accepts
292 return them for Python 3 compatibility as getopt.getopt() don't accepts
293 bytes on Python 3.
293 bytes on Python 3.
294 """
294 """
295 args = [a.decode('latin-1') for a in args]
295 args = [a.decode('latin-1') for a in args]
296 shortlist = shortlist.decode('latin-1')
296 shortlist = shortlist.decode('latin-1')
297 namelist = [a.decode('latin-1') for a in namelist]
297 namelist = [a.decode('latin-1') for a in namelist]
298 opts, args = orig(args, shortlist, namelist)
298 opts, args = orig(args, shortlist, namelist)
299 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
299 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
300 for a in opts]
300 for a in opts]
301 args = [a.encode('latin-1') for a in args]
301 args = [a.encode('latin-1') for a in args]
302 return opts, args
302 return opts, args
303
303
304 def strkwargs(dic):
304 def strkwargs(dic):
305 """
305 """
306 Converts the keys of a python dictonary to str i.e. unicodes so that
306 Converts the keys of a python dictonary to str i.e. unicodes so that
307 they can be passed as keyword arguments as dictonaries with bytes keys
307 they can be passed as keyword arguments as dictonaries with bytes keys
308 can't be passed as keyword arguments to functions on Python 3.
308 can't be passed as keyword arguments to functions on Python 3.
309 """
309 """
310 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
310 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
311 return dic
311 return dic
312
312
313 def byteskwargs(dic):
313 def byteskwargs(dic):
314 """
314 """
315 Converts keys of python dictonaries to bytes as they were converted to
315 Converts keys of python dictonaries to bytes as they were converted to
316 str to pass that dictonary as a keyword argument on Python 3.
316 str to pass that dictonary as a keyword argument on Python 3.
317 """
317 """
318 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
318 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
319 return dic
319 return dic
320
320
321 # TODO: handle shlex.shlex().
321 # TODO: handle shlex.shlex().
322 def shlexsplit(s, comments=False, posix=True):
322 def shlexsplit(s, comments=False, posix=True):
323 """
323 """
324 Takes bytes argument, convert it to str i.e. unicodes, pass that into
324 Takes bytes argument, convert it to str i.e. unicodes, pass that into
325 shlex.split(), convert the returned value to bytes and return that for
325 shlex.split(), convert the returned value to bytes and return that for
326 Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
326 Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
327 """
327 """
328 ret = shlex.split(s.decode('latin-1'), comments, posix)
328 ret = shlex.split(s.decode('latin-1'), comments, posix)
329 return [a.encode('latin-1') for a in ret]
329 return [a.encode('latin-1') for a in ret]
330
330
331 else:
331 else:
332 import cStringIO
332 import cStringIO
333
333
334 xrange = xrange
334 unicode = unicode
335 unicode = unicode
335 bytechr = chr
336 bytechr = chr
336 byterepr = repr
337 byterepr = repr
337 bytestr = str
338 bytestr = str
338 iterbytestr = iter
339 iterbytestr = iter
339 maybebytestr = identity
340 maybebytestr = identity
340 sysbytes = identity
341 sysbytes = identity
341 sysstr = identity
342 sysstr = identity
342 strurl = identity
343 strurl = identity
343 bytesurl = identity
344 bytesurl = identity
344
345
345 # this can't be parsed on Python 3
346 # this can't be parsed on Python 3
346 exec('def raisewithtb(exc, tb):\n'
347 exec('def raisewithtb(exc, tb):\n'
347 ' raise exc, None, tb\n')
348 ' raise exc, None, tb\n')
348
349
349 def fsencode(filename):
350 def fsencode(filename):
350 """
351 """
351 Partial backport from os.py in Python 3, which only accepts bytes.
352 Partial backport from os.py in Python 3, which only accepts bytes.
352 In Python 2, our paths should only ever be bytes, a unicode path
353 In Python 2, our paths should only ever be bytes, a unicode path
353 indicates a bug.
354 indicates a bug.
354 """
355 """
355 if isinstance(filename, str):
356 if isinstance(filename, str):
356 return filename
357 return filename
357 else:
358 else:
358 raise TypeError(
359 raise TypeError(
359 "expect str, not %s" % type(filename).__name__)
360 "expect str, not %s" % type(filename).__name__)
360
361
361 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
362 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
362 # better not to touch Python 2 part as it's already working fine.
363 # better not to touch Python 2 part as it's already working fine.
363 fsdecode = identity
364 fsdecode = identity
364
365
365 def getdoc(obj):
366 def getdoc(obj):
366 return getattr(obj, '__doc__', None)
367 return getattr(obj, '__doc__', None)
367
368
368 _notset = object()
369 _notset = object()
369
370
370 def safehasattr(thing, attr):
371 def safehasattr(thing, attr):
371 return getattr(thing, attr, _notset) is not _notset
372 return getattr(thing, attr, _notset) is not _notset
372
373
373 def _getoptbwrapper(orig, args, shortlist, namelist):
374 def _getoptbwrapper(orig, args, shortlist, namelist):
374 return orig(args, shortlist, namelist)
375 return orig(args, shortlist, namelist)
375
376
376 strkwargs = identity
377 strkwargs = identity
377 byteskwargs = identity
378 byteskwargs = identity
378
379
379 oscurdir = os.curdir
380 oscurdir = os.curdir
380 oslinesep = os.linesep
381 oslinesep = os.linesep
381 osname = os.name
382 osname = os.name
382 ospathsep = os.pathsep
383 ospathsep = os.pathsep
383 ospardir = os.pardir
384 ospardir = os.pardir
384 ossep = os.sep
385 ossep = os.sep
385 osaltsep = os.altsep
386 osaltsep = os.altsep
386 stdin = sys.stdin
387 stdin = sys.stdin
387 stdout = sys.stdout
388 stdout = sys.stdout
388 stderr = sys.stderr
389 stderr = sys.stderr
389 if getattr(sys, 'argv', None) is not None:
390 if getattr(sys, 'argv', None) is not None:
390 sysargv = sys.argv
391 sysargv = sys.argv
391 sysplatform = sys.platform
392 sysplatform = sys.platform
392 getcwd = os.getcwd
393 getcwd = os.getcwd
393 sysexecutable = sys.executable
394 sysexecutable = sys.executable
394 shlexsplit = shlex.split
395 shlexsplit = shlex.split
395 bytesio = cStringIO.StringIO
396 bytesio = cStringIO.StringIO
396 stringio = bytesio
397 stringio = bytesio
397 maplist = map
398 maplist = map
398 rangelist = range
399 rangelist = range
399 ziplist = zip
400 ziplist = zip
400 rawinput = raw_input
401 rawinput = raw_input
401 getargspec = inspect.getargspec
402 getargspec = inspect.getargspec
402
403
403 isjython = sysplatform.startswith('java')
404 isjython = sysplatform.startswith('java')
404
405
405 isdarwin = sysplatform == 'darwin'
406 isdarwin = sysplatform == 'darwin'
406 isposix = osname == 'posix'
407 isposix = osname == 'posix'
407 iswindows = osname == 'nt'
408 iswindows = osname == 'nt'
408
409
409 def getoptb(args, shortlist, namelist):
410 def getoptb(args, shortlist, namelist):
410 return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
411 return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
411
412
412 def gnugetoptb(args, shortlist, namelist):
413 def gnugetoptb(args, shortlist, namelist):
413 return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
414 return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
414
415
415 def mkdtemp(suffix=b'', prefix=b'tmp', dir=None):
416 def mkdtemp(suffix=b'', prefix=b'tmp', dir=None):
416 return tempfile.mkdtemp(suffix, prefix, dir)
417 return tempfile.mkdtemp(suffix, prefix, dir)
417
418
418 # text=True is not supported; use util.from/tonativeeol() instead
419 # text=True is not supported; use util.from/tonativeeol() instead
419 def mkstemp(suffix=b'', prefix=b'tmp', dir=None):
420 def mkstemp(suffix=b'', prefix=b'tmp', dir=None):
420 return tempfile.mkstemp(suffix, prefix, dir)
421 return tempfile.mkstemp(suffix, prefix, dir)
421
422
422 # mode must include 'b'ytes as encoding= is not supported
423 # mode must include 'b'ytes as encoding= is not supported
423 def namedtempfile(mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None,
424 def namedtempfile(mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None,
424 delete=True):
425 delete=True):
425 mode = sysstr(mode)
426 mode = sysstr(mode)
426 assert r'b' in mode
427 assert r'b' in mode
427 return tempfile.NamedTemporaryFile(mode, bufsize, suffix=suffix,
428 return tempfile.NamedTemporaryFile(mode, bufsize, suffix=suffix,
428 prefix=prefix, dir=dir, delete=delete)
429 prefix=prefix, dir=dir, delete=delete)
General Comments 0
You need to be logged in to leave comments. Login now