]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
(system): rewrite system() using
[lilypond.git] / python / lilylib.py
1 ################################################################
2 # lilylib.py -- options and stuff
3
4 # source file of the GNU LilyPond music typesetter
5 #
6 # (c) 1998--2006 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8
9 ###  subst:\(^\|[^._a-z]\)\(abspath\|identify\|warranty\|progress\|warning\|error\|exit\|getopt_args\|option_help_str\|options_help_str\|help\|setup_temp\|read_pipe\|system\|cleanup_temp\|strip_extension\|cp_to_dir\|mkdir_p\|init\) *(
10 ###  replace:\1ly.\2 (
11
12 ### subst: \(help_summary\|keep_temp_dir_p\|option_definitions\|original_dir\|program_name\|pseudo_filter_p\|temp_dir\|verbose_p\)
13
14 import __main__
15 import glob
16 import os
17 import re
18 import shutil
19 import string
20 import sys
21 import optparse
22 import subprocess
23
24 ################################################################
25 # Users of python modules should include this snippet
26 # and customize variables below.
27
28 # We'll suffer this path init stuff as long as we don't install our
29 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
30 # it as we do with teTeX on Red Hat Linux: set some environment var
31 # (PYTHONPATH) in profile)
32
33 # If set, LILYPONDPREFIX must take prevalence
34 # if datadir is not set, we're doing a build and LILYPONDPREFIX
35
36 datadir = '@local_lilypond_datadir@'
37 if not os.path.isdir (datadir):
38         datadir = '@lilypond_datadir@'
39 if os.environ.has_key ('LILYPONDPREFIX') :
40         datadir = os.environ['LILYPONDPREFIX']
41         while datadir[-1] == os.sep:
42                 datadir= datadir[:-1]
43
44 sys.path.insert (0, os.path.join (datadir, 'python'))
45
46
47
48
49 localedir = '@localedir@'
50 try:
51         import gettext
52         gettext.bindtextdomain ('lilypond', localedir)
53         gettext.textdomain ('lilypond')
54         _ = gettext.gettext
55 except:
56         def _ (s):
57                 return s
58 underscore = _
59 progress = sys.stderr.write 
60
61
62 def command_name (cmd):
63         # Strip all stuf after command,
64         # deal with "((latex ) >& 1 ) .." too
65         cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
66         return os.path.basename (cmd)
67
68 def system (cmd,
69               ignore_error=False,
70               progress_p=True,
71               be_verbose=False,
72               log_file=None):
73         
74         show_progress= progress_p 
75         name = command_name (cmd)
76         error_log_file = ''
77
78         if be_verbose:
79                 show_progress = 1
80                 progress (_ ("Invoking `%s\'") % cmd)
81         else:
82                 progress ( _("Running %s...") % name)
83
84
85         stdout_setting = None
86         if not show_progress:
87                 stdout_setting = subprocess.PIPE
88                 
89         proc = subprocess.Popen (cmd,
90                                  shell=True,
91                                  universal_newlines=True,
92                                  stdout=stdout_setting,
93                                  stderr=stdout_setting)
94
95         log = ''
96
97         if show_progress:
98                 retval = proc.wait()
99         else:
100                 log = proc.communicate ()
101                 retval = proc.returncode
102
103
104         if retval:
105                 print >>sys.stderr, 'command failed:', cmd
106                 if retval < 0:
107                     print >>sys.stderr, "Child was terminated by signal", -retval
108                 elif retval > 0:
109                     print >>sys.stderr, "Child returned", retval
110
111                 if ignore_error:
112                         print >>sys.stderr, "Error ignored"
113                 else:
114                         if not show_progress:
115                                 print log[0]
116                                 print log[1]
117                         sys.exit (1)
118
119         return abs (retval)
120
121 def strip_extension (f, ext):
122         (p, e) = os.path.splitext (f)
123         if e == ext:
124                 e = ''
125         return p + e
126
127
128 def search_exe_path (name):
129         p = os.environ['PATH']
130         exe_paths = string.split (p, ':')
131         for e in exe_paths:
132                 full = os.path.join (e, name)
133                 if os.path.exists (full):
134                         return full
135         return None
136
137
138 def print_environment ():
139         for (k,v) in os.environ.items ():
140                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
141
142
143 def ps_page_count (ps_name):
144         header = open (ps_name).read (1024)
145         m = re.search ('\n%%Pages: ([0-9]+)', header)
146         if m:
147                 return string.atoi (m.group (1))
148         return 0
149
150 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
151     def format_heading(self, heading):
152             if heading:
153                     return heading[0].upper() + heading[1:] + ':\n'
154             return ''
155     def format_option_strings(self, option):
156             sep = ' '
157             if option._short_opts and option._long_opts:
158                     sep = ','
159
160             metavar = ''
161             if option.takes_value():
162                     metavar = '=%s' % option.metavar or option.dest.upper()
163
164             return "%3s%s %s%s" % (" ".join (option._short_opts),
165                                    sep,
166                                    " ".join (option._long_opts),
167                                    metavar)
168
169     def format_usage(self, usage):
170         return _("Usage: %s\n") % usage
171     
172     def format_description(self, description):
173             return description
174
175 def get_option_parser (*args, **kwargs): 
176         p = optparse.OptionParser (*args, **kwargs)
177         p.formatter = NonDentedHeadingFormatter () 
178         return p