FIX: subprocess.check_output was added to python 2.7, not 2.5
[freefoam.git] / data / python / FreeFOAM / compat.py
blob130784b5d83418e1c06691ccee86c860b8c5689d
1 #-------------------------------------------------------------------------------
2 # ______ _ ____ __ __
3 # | ____| _| |_ / __ \ /\ | \/ |
4 # | |__ _ __ ___ ___ / \| | | | / \ | \ / |
5 # | __| '__/ _ \/ _ ( (| |) ) | | |/ /\ \ | |\/| |
6 # | | | | | __/ __/\_ _/| |__| / ____ \| | | |
7 # |_| |_| \___|\___| |_| \____/_/ \_\_| |_|
9 # FreeFOAM: The Cross-Platform CFD Toolkit
11 # Copyright (C) 2008-2011 Michael Wild <themiwi@users.sf.net>
12 # Gerber van der Graaf <gerber_graaf@users.sf.net>
13 # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software
14 # Foundation; All Rights Reserved
15 #-------------------------------------------------------------------------------
16 # License
17 # This file is part of FreeFOAM.
19 # FreeFOAM is free software; you can redistribute it and/or modify it
20 # under the terms of the GNU General Public License as published by the
21 # Free Software Foundation; either version 2 of the License, or (at your
22 # option) any later version.
24 # FreeFOAM is distributed in the hope that it will be useful, but WITHOUT
25 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
26 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 # for more details.
29 # You should have received a copy of the GNU General Public License
30 # along with FreeFOAM; if not, write to the Free Software Foundation,
31 # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
33 # Some of the below functions have been backported from Python. They are
34 # licensed under the Python Software Foundation License version 2. The full
35 # license text is available at http://docs.python.org/license.html. Notably,
36 # the functions _nt_relpath and _posix_relpath are adapted versions of
37 # ntpath.relpath and posixpath.relpath, respectively and are copyrighted to
38 # the Python Software Foundation. _check_call and _check_output were modified
39 # from subprocess.check_call and subprocess.check_output which are
40 # copyrighted to Peter Astrand <astrand@lysator.liu.se>.
42 # Description
43 # Compatibility functions that make Python 3.x code work with 2.x
44 # interpreters.
46 #-------------------------------------------------------------------------------
48 import sys as _sys
49 import os.path as _op
50 import os as _os
51 import subprocess as _subprocess
53 def echo(*args, **kwargs):
54 """print() replacement which does not depend on the Python version"""
55 if 'sep' in kwargs:
56 sep = kwargs['sep']
57 else:
58 sep = ' '
59 if 'end' in kwargs:
60 end = kwargs['end']
61 else:
62 end = '\n'
63 if 'file' in kwargs:
64 file = kwargs['file']
65 else:
66 file = _sys.stdout
67 file.write(str(sep).join(map(str, args)))
68 end = str(end)
69 if len(end):
70 file.write(end)
72 # check whether Python version is < 3.0
73 if _sys.hexversion < 0x030000f0:
74 # replace the standard functions
75 import itertools
76 filter = itertools.ifilter
77 map = itertools.imap
78 zip = itertools.izip
79 repr = unicode
80 range = xrange
81 import HTMLParser
82 else:
83 callable = None
84 xrange = None
85 import html.parser as HTMLParser
87 # check whether Python version is < 2.6
88 if _sys.hexversion < 0x020600f0:
89 def _posix_relpath(path, start=_os.curdir):
90 """Return a relative version of a path, POSIX version"""
92 if not path:
93 raise ValueError("no path specified")
95 start_list = _op.abspath(start).split(_op.sep)
96 path_list = _op.abspath(path).split(_op.sep)
98 # Work out how much of the filepath is shared by start and path.
99 i = len(_op.commonprefix([start_list, path_list]))
101 rel_list = [_op.pardir] * (len(start_list)-i) + path_list[i:]
102 if not rel_list:
103 return _os.curdir
104 return _op.join(*rel_list)
106 def _nt_relpath(path, start=_os.curdir):
107 """Return a relative version of a path, Windows version"""
109 if not path:
110 raise ValueError("no path specified")
111 start_list = _op.abspath(start).split(_op.sep)
112 path_list = _op.abspath(path).split(_op.sep)
113 if start_list[0].lower() != path_list[0].lower():
114 unc_path, rest = _op.splitunc(path)
115 unc_start, rest = _op.splitunc(start)
116 if bool(unc_path) ^ bool(unc_start):
117 raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
118 % (path, start))
119 else:
120 raise ValueError("path is on drive %s, start on drive %s"
121 % (path_list[0], start_list[0]))
122 # Work out how much of the filepath is shared by start and path.
123 for i in range(min(len(start_list), len(path_list))):
124 if start_list[i].lower() != path_list[i].lower():
125 break
126 else:
127 i += 1
129 rel_list = [_op.pardir] * (len(start_list)-i) + path_list[i:]
130 if not rel_list:
131 return _os.curdir
132 return _op.join(*rel_list)
134 # provide os.path.relpath
135 if _os.name == 'posix':
136 _op.relpath = _posix_relpath
137 elif _os.name == 'nt':
138 _op.relpath = _nt_relpath
139 else:
140 raise Exception('No implementation of os.path.relpath available')
142 # check whether Python version is < 2.5
143 if _sys.hexversion < 0x020500f0:
144 # there is no BaseException class
145 BaseException = Exception
147 # there is no subprocess.check_call() function
148 def _check_call(*popernargs, **kwargs):
149 retcode = _subprocess.call(*popenargs, **kwargs)
150 if retcode:
151 cmd = kwargs.get("args")
152 if cmd is None:
153 cmd = popenargs[0]
154 raise _subprocess.CalledProcessError(retcode, cmd)
155 return 0
156 _subprocess.check_call = _check_call
158 # check whether Python version is < 2.7
159 if _sys.hexversion < 0x020700f0:
160 # there is no subprocess.check_output() function
161 def _check_output(*popenargs, **kwargs):
162 if 'stdout' in kwargs:
163 raise ValueError(
164 'stdout argument not allowed, it will be overridden.')
165 process = _subprocess.Popen(
166 stdout=_subprocess.PIPE, *popenargs, **kwargs)
167 output, unused_err = process.communicate()
168 retcode = process.poll()
169 if retcode:
170 cmd = kwargs.get("args")
171 if cmd is None:
172 cmd = popenargs[0]
173 raise _subprocess.CalledProcessError(retcode, cmd, output=output)
174 return output
175 _subprocess.check_output = _check_output
177 # ------------------------- vim: set sw=3 sts=3 et: --------------- end-of-file