new-fingering-engraver.cc: get 'script-priority from grobs, if set.
[lilypond.git] / python / lilylib.py
blob27dd98deabeea5ee439f538467a2065a537c37cb
1 ###############################################################
2 # lilylib.py -- options and stuff
3 #
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 # Jan Nieuwenhuizen <janneke@gnu.org>
9 import __main__
10 import glob
11 import os
12 import re
13 import shutil
14 import sys
15 import optparse
17 ################################################################
18 # Users of python modules should include this snippet
19 # and customize variables below.
21 # We'll suffer this path init stuff as long as we don't install our
22 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
23 # it as we do with teTeX on Red Hat Linux: set some environment var
24 # (PYTHONPATH) in profile)
26 # If set, LILYPOND_DATADIR must take prevalence
27 # if datadir is not set, we're doing a build and LILYPOND_DATADIR
29 datadir = '@local_lilypond_datadir@'
30 if not os.path.isdir (datadir):
31 datadir = '@lilypond_datadir@'
32 if os.environ.has_key ('LILYPOND_DATADIR') :
33 datadir = os.environ['LILYPOND_DATADIR']
34 while datadir[-1] == os.sep:
35 datadir= datadir[:-1]
37 sys.path.insert (0, os.path.join (datadir, 'python'))
40 # Python 2.5 only accepts strings with proper Python internal encoding
41 # (i.e. ASCII or Unicode) when writing to stdout/stderr, so we must
42 # use ugettext iso gettext, and encode the string when writing to
43 # stdout/stderr
45 localedir = '@localedir@'
46 try:
47 import gettext
48 t = gettext.translation ('lilypond', localedir)
49 _ = t.ugettext
50 except:
51 def _ (s):
52 return s
53 underscore = _
55 # Urg, Python 2.4 does not define stderr/stdout encoding
56 # Maybe guess encoding from LANG/LC_ALL/LC_CTYPE?
58 def encoded_write(f, s):
59 f.write (s.encode (f.encoding or 'utf_8'))
61 # ugh, Python 2.5 optparse requires Unicode strings in some argument
62 # functions, and refuse them in some other places
63 def display_encode (s):
64 return s.encode (sys.stderr.encoding or 'utf_8')
66 def stderr_write (s):
67 encoded_write (sys.stderr, s)
69 progress = stderr_write
71 def require_python_version ():
72 if sys.hexversion < 0x02040000:
73 stderr_write ("Python 2.4 or newer is required to run this program.\n\
74 Please upgrade Python from http://python.org/download/, and if you use MacOS X,\n\
75 please read 'Setup for MacOS X' in Application Usage.")
76 os.system ("open http://python.org/download/")
77 sys.exit (2)
79 # Modified version of the commands.mkarg(x), which always uses
80 # double quotes (since Windows can't handle the single quotes:
81 def mkarg(x):
82 s = ' "'
83 for c in x:
84 if c in '\\$"`':
85 s = s + '\\'
86 s = s + c
87 s = s + '"'
88 return s
90 def command_name (cmd):
91 # Strip all stuf after command,
92 # deal with "((latex ) >& 1 ) .." too
93 cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
94 return os.path.basename (cmd)
96 def subprocess_system (cmd,
97 ignore_error=False,
98 progress_p=True,
99 be_verbose=False,
100 log_file=None):
101 import subprocess
103 show_progress= progress_p
104 name = command_name (cmd)
105 error_log_file = ''
107 if be_verbose:
108 show_progress = 1
109 progress (_ ("Invoking `%s\'") % cmd)
110 else:
111 progress ( _("Running %s...") % name)
114 stdout_setting = None
115 if not show_progress:
116 stdout_setting = subprocess.PIPE
118 proc = subprocess.Popen (cmd,
119 shell=True,
120 universal_newlines=True,
121 stdout=stdout_setting,
122 stderr=stdout_setting)
124 log = ''
126 if show_progress:
127 retval = proc.wait()
128 else:
129 log = proc.communicate ()
130 retval = proc.returncode
133 if retval:
134 print >>sys.stderr, 'command failed:', cmd
135 if retval < 0:
136 print >>sys.stderr, "Child was terminated by signal", -retval
137 elif retval > 0:
138 print >>sys.stderr, "Child returned", retval
140 if ignore_error:
141 print >>sys.stderr, "Error ignored"
142 else:
143 if not show_progress:
144 print log[0]
145 print log[1]
146 sys.exit (1)
148 return abs (retval)
150 def ossystem_system (cmd,
151 ignore_error=False,
152 progress_p=True,
153 be_verbose=False,
154 log_file=None):
157 name = command_name (cmd)
158 if be_verbose:
159 show_progress = 1
160 progress (_ ("Invoking `%s\'") % cmd)
161 else:
162 progress ( _("Running %s...") % name)
164 retval = os.system (cmd)
165 if retval:
166 print >>sys.stderr, 'command failed:', cmd
167 if retval < 0:
168 print >>sys.stderr, "Child was terminated by signal", -retval
169 elif retval > 0:
170 print >>sys.stderr, "Child returned", retval
172 if ignore_error:
173 print >>sys.stderr, "Error ignored"
174 else:
175 sys.exit (1)
177 return abs (retval)
180 system = subprocess_system
181 if sys.platform == 'mingw32':
183 ## subprocess x-compile doesn't work.
184 system = ossystem_system
186 def strip_extension (f, ext):
187 (p, e) = os.path.splitext (f)
188 if e == ext:
189 e = ''
190 return p + e
193 def search_exe_path (name):
194 p = os.environ['PATH']
195 exe_paths = p.split (':')
196 for e in exe_paths:
197 full = os.path.join (e, name)
198 if os.path.exists (full):
199 return full
200 return None
203 def print_environment ():
204 for (k,v) in os.environ.items ():
205 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
207 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
208 def format_heading(self, heading):
209 if heading:
210 return heading[0].upper() + heading[1:] + ':\n'
211 return ''
212 def format_option_strings(self, option):
213 sep = ' '
214 if option._short_opts and option._long_opts:
215 sep = ','
217 metavar = ''
218 if option.takes_value():
219 metavar = '=%s' % option.metavar or option.dest.upper()
221 return "%3s%s %s%s" % (" ".join (option._short_opts),
222 sep,
223 " ".join (option._long_opts),
224 metavar)
226 def format_usage(self, usage):
227 return _("Usage: %s") % usage + '\n'
229 def format_description(self, description):
230 return description
232 def get_option_parser (*args, **kwargs):
233 p = optparse.OptionParser (*args, **kwargs)
234 p.formatter = NonDentedHeadingFormatter ()
235 return p