This repository has been archived by the owner on Dec 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
dialog.py
1685 lines (1353 loc) · 63.9 KB
/
dialog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# dialog.py --- A python interface to the Linux "dialog" utility
# Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov
# Copyright (C) 2002, 2003, 2004 Florent Rougon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Python interface to dialog-like programs.
This module provides a Python interface to dialog-like programs such
as `dialog', `Xdialog' and `whiptail'.
It provides a Dialog class that retains some parameters such as the
program name and path as well as the values to pass as DIALOG*
environment variables to the chosen program.
For a quick start, you should look at the demo.py file that comes
with pythondialog. It demonstrates a simple use of each widget
offered by the Dialog class.
See the Dialog class documentation for general usage information,
list of available widgets and ways to pass options to dialog.
Notable exceptions
------------------
Here is the hierarchy of notable exceptions raised by this module:
error
ExecutableNotFound
BadPythonDialogUsage
PythonDialogSystemError
PythonDialogIOError
PythonDialogOSError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogReModuleError
UnexpectedDialogOutput
DialogTerminatedBySignal
DialogError
UnableToCreateTemporaryDirectory
PythonDialogBug
ProbablyPythonBug
As you can see, every exception `exc' among them verifies:
issubclass(exc, error)
so if you don't need fine-grained error handling, simply catch
`error' (which will probably be accessible as dialog.error from your
program) and you should be safe.
"""
from __future__ import nested_scopes
import sys, os, tempfile, random, string, re, types
# Python < 2.3 compatibility
if sys.hexversion < 0x02030000:
# The assignments would work with Python >= 2.3 but then, pydoc
# shows them in the DATA section of the module...
True = 0 == 0
False = 0 == 1
# Exceptions raised by this module
#
# When adding, suppressing, renaming exceptions or changing their
# hierarchy, don't forget to update the module's docstring.
class error(Exception):
"""Base class for exceptions in pythondialog."""
def __init__(self, message=None):
self.message = message
def __str__(self):
return "<%s: %s>" % (self.__class__.__name__, self.message)
def complete_message(self):
if self.message:
return "%s: %s" % (self.ExceptionShortDescription, self.message)
else:
return "%s" % self.ExceptionShortDescription
ExceptionShortDescription = "pythondialog generic exception"
# For backward-compatibility
#
# Note: this exception was not documented (only the specific ones were), so
# the backward-compatibility binding could be removed relatively easily.
PythonDialogException = error
class ExecutableNotFound(error):
"""Exception raised when the dialog executable can't be found."""
ExceptionShortDescription = "Executable not found"
class PythonDialogBug(error):
"""Exception raised when pythondialog finds a bug in his own code."""
ExceptionShortDescription = "Bug in pythondialog"
# Yeah, the "Probably" makes it look a bit ugly, but:
# - this is more accurate
# - this avoids a potential clash with an eventual PythonBug built-in
# exception in the Python interpreter...
class ProbablyPythonBug(error):
"""Exception raised when pythondialog behaves in a way that seems to \
indicate a Python bug."""
ExceptionShortDescription = "Bug in python, probably"
class BadPythonDialogUsage(error):
"""Exception raised when pythondialog is used in an incorrect way."""
ExceptionShortDescription = "Invalid use of pythondialog"
class PythonDialogSystemError(error):
"""Exception raised when pythondialog cannot perform a "system \
operation" (e.g., a system call) that should work in "normal" situations.
This is a convenience exception: PythonDialogIOError, PythonDialogOSError
and PythonDialogErrorBeforeExecInChildProcess all derive from this
exception. As a consequence, watching for PythonDialogSystemError instead
of the aformentioned exceptions is enough if you don't need precise
details about these kinds of errors.
Don't confuse this exception with Python's builtin SystemError
exception.
"""
ExceptionShortDescription = "System error"
class PythonDialogIOError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an IOError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "IO error"
class PythonDialogOSError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an OSError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "OS error"
class PythonDialogErrorBeforeExecInChildProcess(PythonDialogSystemError):
"""Exception raised when an exception is caught in a child process \
before the exec sytem call (included).
This can happen in uncomfortable situations like when the system is out
of memory or when the maximum number of open file descriptors has been
reached. This can also happen if the dialog-like program was removed
(or if it is has been made non-executable) between the time we found it
with _find_in_path and the time the exec system call attempted to
execute it...
"""
ExceptionShortDescription = "Error in a child process before the exec " \
"system call"
class PythonDialogReModuleError(PythonDialogSystemError):
"""Exception raised when pythondialog catches a re.error exception."""
ExceptionShortDescription = "'re' module error"
class UnexpectedDialogOutput(error):
"""Exception raised when the dialog-like program returns something not \
expected by pythondialog."""
ExceptionShortDescription = "Unexpected dialog output"
class DialogTerminatedBySignal(error):
"""Exception raised when the dialog-like program is terminated by a \
signal."""
ExceptionShortDescription = "dialog-like terminated by a signal"
class DialogError(error):
"""Exception raised when the dialog-like program exits with the \
code indicating an error."""
ExceptionShortDescription = "dialog-like terminated due to an error"
class UnableToCreateTemporaryDirectory(error):
"""Exception raised when we cannot create a temporary directory."""
ExceptionShortDescription = "unable to create a temporary directory"
# Values accepted for checklists
try:
_on_rec = re.compile(r"on", re.IGNORECASE)
_off_rec = re.compile(r"off", re.IGNORECASE)
_calendar_date_rec = re.compile(
r"(?P<day>\d\d)/(?P<month>\d\d)/(?P<year>\d\d\d\d)$")
_timebox_time_rec = re.compile(
r"(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)$")
except re.error, v:
raise PythonDialogReModuleError(v)
# This dictionary allows us to write the dialog common options in a Pythonic
# way (e.g. dialog_instance.checklist(args, ..., title="Foo", no_shadow=1)).
#
# Options such as --separate-output should obviously not be set by the user
# since they affect the parsing of dialog's output:
_common_args_syntax = {
"aspect": lambda ratio: ("--aspect", str(ratio)),
"backtitle": lambda backtitle: ("--backtitle", backtitle),
"beep": lambda enable: _simple_option("--beep", enable),
"beep_after": lambda enable: _simple_option("--beep-after", enable),
# Warning: order = y, x!
"begin": lambda coords: ("--begin", str(coords[0]), str(coords[1])),
"cancel": lambda string: ("--cancel-label", string),
"cancel_label": lambda string: ("--cancel-label", string),
"clear": lambda enable: _simple_option("--clear", enable),
"colors": lambda enable: _simple_option("--colors", enable),
"cr_wrap": lambda enable: _simple_option("--cr-wrap", enable),
"create_rc": lambda file: ("--create-rc", file),
"defaultno": lambda enable: _simple_option("--defaultno", enable),
"default_item": lambda string: ("--default-item", string),
"help": lambda enable: _simple_option("--help", enable),
"help_button": lambda enable: _simple_option("--help-button", enable),
"help_label": lambda string: ("--help-label", string),
"insecure": lambda enable: _simple_option("--insecure", enable),
"ignore": lambda enable: _simple_option("--ignore", enable),
"item_help": lambda enable: _simple_option("--item-help", enable),
"max_input": lambda size: ("--max-input", str(size)),
"no_kill": lambda enable: _simple_option("--no-kill", enable),
"no_cancel": lambda enable: _simple_option("--no-cancel", enable),
"nocancel": lambda enable: _simple_option("--nocancel", enable),
"no_shadow": lambda enable: _simple_option("--no-shadow", enable),
"no_label": lambda string: ("--no-label", string),
"ok_label": lambda string: ("--ok-label", string),
"print_maxsize": lambda enable: _simple_option("--print-maxsize",
enable),
"print_size": lambda enable: _simple_option("--print-size", enable),
"print_version": lambda enable: _simple_option("--print-version",
enable),
"separate_output": lambda enable: _simple_option("--separate-output",
enable),
"separate_widget": lambda string: ("--separate-widget", string),
"shadow": lambda enable: _simple_option("--shadow", enable),
"size_err": lambda enable: _simple_option("--size-err", enable),
"sleep": lambda secs: ("--sleep", str(secs)),
"stderr": lambda enable: _simple_option("--stderr", enable),
"stdout": lambda enable: _simple_option("--stdout", enable),
"tab_correct": lambda enable: _simple_option("--tab-correct", enable),
"tab_len": lambda n: ("--tab-len", str(n)),
"timeout": lambda secs: ("--timeout", str(secs)),
"title": lambda title: ("--title", title),
"trim": lambda enable: _simple_option("--trim", enable),
"version": lambda enable: _simple_option("--version", enable),
"yes_label": lambda string: ("--yes-label", string)}
def _simple_option(option, enable):
"""Turn on or off the simplest dialog Common Options."""
if enable:
return (option,)
else:
# This will not add any argument to the command line
return ()
def _find_in_path(prog_name):
"""Search an executable in the PATH.
If PATH is not defined, the default path ":/bin:/usr/bin" is
used.
Return a path to the file or None if no readable and executable
file is found.
Notable exception: PythonDialogOSError
"""
try:
# Note that the leading empty component in the default value for PATH
# could lead to the returned path not being absolute.
PATH = os.getenv("PATH", ":/bin:/usr/bin") # see the execvp(3) man page
for dir in string.split(PATH, ":"):
file_path = os.path.join(dir, prog_name)
if os.path.isfile(file_path) \
and os.access(file_path, os.R_OK | os.X_OK):
return file_path
return None
except os.error, v:
raise PythonDialogOSError(v.strerror)
def _path_to_executable(f):
"""Find a path to an executable.
Find a path to an executable, using the same rules as the POSIX
exec*p functions (see execvp(3) for instance).
If `f' contains a '/', it is assumed to be a path and is simply
checked for read and write permissions; otherwise, it is looked
for according to the contents of the PATH environment variable,
which defaults to ":/bin:/usr/bin" if unset.
The returned path is not necessarily absolute.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
try:
if '/' in f:
if os.path.isfile(f) and \
os.access(f, os.R_OK | os.X_OK):
res = f
else:
raise ExecutableNotFound("%s cannot be read and executed" % f)
else:
res = _find_in_path(f)
if res is None:
raise ExecutableNotFound(
"can't find the executable for the dialog-like "
"program")
except os.error, v:
raise PythonDialogOSError(v.strerror)
return res
def _to_onoff(val):
"""Convert boolean expressions to "on" or "off"
This function converts every non-zero integer as well as "on",
"ON", "On" and "oN" to "on" and converts 0, "off", "OFF", etc. to
"off".
Notable exceptions:
PythonDialogReModuleError
BadPythonDialogUsage
"""
if type(val) == types.IntType:
if val:
return "on"
else:
return "off"
elif type(val) == types.StringType:
try:
if _on_rec.match(val):
return "on"
elif _off_rec.match(val):
return "off"
except re.error, v:
raise PythonDialogReModuleError(v)
else:
raise BadPythonDialogUsage("invalid boolean value: %s" % val)
def _compute_common_args(dict):
"""Compute the list of arguments for dialog common options.
Compute a list of the command-line arguments to pass to dialog
from a keyword arguments dictionary for options listed as "common
options" in the manual page for dialog. These are the options
that are not tied to a particular widget.
This allows to specify these options in a pythonic way, such as:
d.checklist(<usual arguments for a checklist>,
title="...",
backtitle="...")
instead of having to pass them with strings like "--title foo" or
"--backtitle bar".
Notable exceptions: None
"""
args = []
for key in dict.keys():
args.extend(_common_args_syntax[key](dict[key]))
return args
def _create_temporary_directory():
"""Create a temporary directory (securely).
Return the directory path.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogOSError
- exceptions raised by the tempfile module (which are
unfortunately not mentioned in its documentation, at
least in Python 2.3.3...)
"""
find_temporary_nb_attempts = 5
for i in range(find_temporary_nb_attempts):
try:
# Using something >= 2**31 causes an error in Python 2.2...
tmp_dir = os.path.join(tempfile.gettempdir(),
"%s-%u" \
% ("pythondialog",
random.randint(0, 2**30-1)))
except os.error, v:
raise PythonDialogOSError(v.strerror)
try:
os.mkdir(tmp_dir, 0700)
except os.error:
continue
else:
break
else:
raise UnableToCreateTemporaryDirectory(
"somebody may be trying to attack us")
return tmp_dir
# DIALOG_OK, DIALOG_CANCEL, etc. are environment variables controlling
# dialog's exit status in the corresponding situation.
#
# Note:
# - 127 must not be used for any of the DIALOG_* values. It is used
# when a failure occurs in the child process before it exec()s
# dialog (where "before" includes a potential exec() failure).
# - 126 is also used (although in presumably rare situations).
_dialog_exit_status_vars = { "OK": 0,
"CANCEL": 1,
"ESC": 2,
"ERROR": 3,
"EXTRA": 4,
"HELP": 5 }
# Main class of the module
class Dialog:
"""Class providing bindings for dialog-compatible programs.
This class allows you to invoke dialog or a compatible program in
a pythonic way to build quicky and easily simple but nice text
interfaces.
An application typically creates one instance of the Dialog class
and uses it for all its widgets, but it is possible to use
concurrently several instances of this class with different
parameters (such as the background title) if you have the need
for this.
The exit code (exit status) returned by dialog is to be
compared with the DIALOG_OK, DIALOG_CANCEL, DIALOG_ESC,
DIALOG_ERROR, DIALOG_EXTRA and DIALOG_HELP attributes of the
Dialog instance (they are integers).
Note: although this class does all it can to allow the caller to
differentiate between the various reasons that caused a
dialog box to be closed, its backend, dialog 0.9a-20020309a
for my tests, doesn't always return DIALOG_ESC when the
user presses the ESC key, but often returns DIALOG_ERROR
instead. The exit codes returned by the corresponding
Dialog methods are of course just as wrong in these cases.
You've been warned.
Public methods of the Dialog class (mainly widgets)
---------------------------------------------------
The Dialog class has the following methods:
add_persistent_args
calendar
checklist
form
fselect
gauge_start
gauge_update
gauge_stop
infobox
inputbox
menu
msgbox
passwordbox
passwordform
radiolist
scrollbox
tailbox
textbox
timebox
yesno
clear (obsolete)
setBackgroundTitle (obsolete)
Passing dialog "Common Options"
-------------------------------
Every widget method has a **kwargs argument allowing you to pass
dialog so-called Common Options (see the dialog(1) manual page)
to dialog for this widget call. For instance, if `d' is a Dialog
instance, you can write:
d.checklist(args, ..., title="A Great Title", no_shadow=1)
The no_shadow option is worth looking at:
1. It is an option that takes no argument as far as dialog is
concerned (unlike the "--title" option, for instance). When
you list it as a keyword argument, the option is really
passed to dialog only if the value you gave it evaluates to
true, e.g. "no_shadow=1" will cause "--no-shadow" to be
passed to dialog whereas "no_shadow=0" will cause this
option not to be passed to dialog at all.
2. It is an option that has a hyphen (-) in its name, which you
must change into an underscore (_) to pass it as a Python
keyword argument. Therefore, "--no-shadow" is passed by
giving a "no_shadow=1" keyword argument to a Dialog method
(the leading two dashes are also consistently removed).
Exceptions
----------
Please refer to the specific methods' docstrings or simply to the
module's docstring for a list of all exceptions that might be
raised by this class' methods.
"""
def __init__(self, dialog="dialog", DIALOGRC=None, compat="dialog",
use_stdout=None):
"""Constructor for Dialog instances.
dialog -- name of (or path to) the dialog-like program to
use; if it contains a '/', it is assumed to be a
path and is used as is; otherwise, it is looked
for according to the contents of the PATH
environment variable, which defaults to
":/bin:/usr/bin" if unset.
DIALOGRC -- string to pass to the dialog-like program as the
DIALOGRC environment variable, or None if no
modification to the environment regarding this
variable should be done in the call to the
dialog-like program
compat -- compatibility mode (see below)
The officially supported dialog-like program in pythondialog
is the well-known dialog program written in C, based on the
ncurses library. It is also known as cdialog and its home
page is currently (2004-03-15) located at:
http://dickey.his.com/dialog/dialog.html
If you want to use a different program such as Xdialog, you
should indicate the executable file name with the `dialog'
argument *and* the compatibility type that you think it
conforms to with the `compat' argument. Currently, `compat'
can be either "dialog" (for dialog; this is the default) or
"Xdialog" (for, well, Xdialog).
The `compat' argument allows me to cope with minor
differences in behaviour between the various programs
implementing the dialog interface (not the text or graphical
interface, I mean the "API"). However, having to support
various APIs simultaneously is a bit ugly and I would really
prefer you to report bugs to the relevant maintainers when
you find incompatibilities with dialog. This is for the
benefit of pretty much everyone that relies on the dialog
interface.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
# DIALOGRC differs from the other DIALOG* variables in that:
# 1. It should be a string if not None
# 2. We may very well want it to be unset
if DIALOGRC is not None:
self.DIALOGRC = DIALOGRC
# After reflexion, I think DIALOG_OK, DIALOG_CANCEL, etc.
# should never have been instance attributes (I cannot see a
# reason why the user would want to change their values or
# even read them), but it is a bit late, now. So, we set them
# based on the (global) _dialog_exit_status_vars.keys.
for var in _dialog_exit_status_vars.keys():
varname = "DIALOG_" + var
setattr(self, varname, _dialog_exit_status_vars[var])
self._dialog_prg = _path_to_executable(dialog)
self.compat = compat
self.dialog_persistent_arglist = []
# Use stderr or stdout?
if self.compat == "Xdialog":
# Default to stdout if Xdialog
self.use_stdout = True
else:
self.use_stdout = False
if use_stdout != None:
# Allow explicit setting
self.use_stdout = use_stdout
if self.use_stdout:
self.add_persistent_args(["--stdout"])
def add_persistent_args(self, arglist):
self.dialog_persistent_arglist.extend(arglist)
# For compatibility with the old dialog...
def setBackgroundTitle(self, text):
"""Set the background title for dialog.
This method is obsolete. Please remove calls to it from your
programs.
"""
self.add_persistent_args(("--backtitle", text))
def _call_program(self, redirect_child_stdin, cmdargs, **kwargs):
"""Do the actual work of invoking the dialog-like program.
Communication with the dialog-like program is performed
through one or two pipes, depending on
`redirect_child_stdin'. There is always one pipe that is
created to allow the parent process to read what dialog
writes on its standard error stream.
If `redirect_child_stdin' is True, an additional pipe is
created whose reading end is connected to dialog's standard
input. This is used by the gauge widget to feed data to
dialog.
Beware when interpreting the return value: the length of the
returned tuple depends on `redirect_child_stdin'.
Notable exception: PythonDialogOSError (if pipe() or close()
system calls fail...)
"""
# We want to define DIALOG_OK, DIALOG_CANCEL, etc. in the
# environment of the child process so that we know (and
# even control) the possible dialog exit statuses.
new_environ = {}
new_environ.update(os.environ)
for var in _dialog_exit_status_vars:
varname = "DIALOG_" + var
new_environ[varname] = str(getattr(self, varname))
if hasattr(self, "DIALOGRC"):
new_environ["DIALOGRC"] = self.DIALOGRC
# Create:
# - a pipe so that the parent process can read dialog's output on
# stdout/stderr
# - a pipe so that the parent process can feed data to dialog's
# stdin (this is needed for the gauge widget) if
# redirect_child_stdin is True
try:
# rfd = File Descriptor for Reading
# wfd = File Descriptor for Writing
(child_rfd, child_wfd) = os.pipe()
if redirect_child_stdin:
(child_stdin_rfd, child_stdin_wfd) = os.pipe()
except os.error, v:
raise PythonDialogOSError(v.strerror)
child_pid = os.fork()
if child_pid == 0:
# We are in the child process. We MUST NOT raise any exception.
try:
# The child process doesn't need these file descriptors
os.close(child_rfd)
if redirect_child_stdin:
os.close(child_stdin_wfd)
# We want:
# - dialog's output on stderr/stdout to go to child_wfd
# - data written to child_stdin_wfd to go to dialog's stdin
# if redirect_child_stdin is True
if self.use_stdout:
os.dup2(child_wfd, 1)
else:
os.dup2(child_wfd, 2)
if redirect_child_stdin:
os.dup2(child_stdin_rfd, 0)
arglist = [self._dialog_prg] + \
self.dialog_persistent_arglist + \
_compute_common_args(kwargs) + \
cmdargs
# Insert here the contents of the DEBUGGING file if you want
# to obtain a handy string of the complete command line with
# arguments quoted for the shell and environment variables
# set.
os.execve(self._dialog_prg, arglist, new_environ)
except:
os._exit(127)
# Should not happen unless there is a bug in Python
os._exit(126)
# We are in the father process.
#
# It is essential to close child_wfd, otherwise we will never
# see EOF while reading on child_rfd and the parent process
# will block forever on the read() call.
# [ after the fork(), the "reference count" of child_wfd from
# the operating system's point of view is 2; after the child exits,
# it is 1 until the father closes it itself; then it is 0 and a read
# on child_rfd encounters EOF once all the remaining data in
# the pipe has been read. ]
try:
os.close(child_wfd)
if redirect_child_stdin:
os.close(child_stdin_rfd)
return (child_pid, child_rfd, child_stdin_wfd)
else:
return (child_pid, child_rfd)
except os.error, v:
raise PythonDialogOSError(v.strerror)
def _wait_for_program_termination(self, child_pid, child_rfd):
"""Wait for a dialog-like process to terminate.
This function waits for the specified process to terminate,
raises the appropriate exceptions in case of abnormal
termination and returns the exit status and standard error
output of the process as a tuple: (exit_code, stderr_string).
`child_rfd' must be the file descriptor for the
reading end of the pipe created by self._call_program()
whose writing end was connected by self._call_program() to
the child process's standard error.
This function reads the process's output on standard error
from `child_rfd' and closes this file descriptor once
this is done.
Notable exceptions:
DialogTerminatedBySignal
DialogError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogIOError
PythonDialogBug
ProbablyPythonBug
"""
exit_info = os.waitpid(child_pid, 0)[1]
if os.WIFEXITED(exit_info):
exit_code = os.WEXITSTATUS(exit_info)
# As we wait()ed for the child process to terminate, there is no
# need to call os.WIFSTOPPED()
elif os.WIFSIGNALED(exit_info):
raise DialogTerminatedBySignal("the dialog-like program was "
"terminated by signal %u" %
os.WTERMSIG(exit_info))
else:
raise PythonDialogBug("please report this bug to the "
"pythondialog maintainers")
if exit_code == self.DIALOG_ERROR:
raise DialogError("the dialog-like program exited with "
"code %d (was passed to it as the DIALOG_ERROR "
"environment variable)" % exit_code)
elif exit_code == 127:
raise PythonDialogErrorBeforeExecInChildProcess(
"perhaps the dialog-like program could not be executed; "
"perhaps the system is out of memory; perhaps the maximum "
"number of open file descriptors has been reached")
elif exit_code == 126:
raise ProbablyPythonBug(
"a child process returned with exit status 126; this might "
"be the exit status of the dialog-like program, for some "
"unknown reason (-> probably a bug in the dialog-like "
"program); otherwise, we have probably found a python bug")
# We might want to check here whether exit_code is really one of
# DIALOG_OK, DIALOG_CANCEL, etc. However, I prefer not doing it
# because it would break pythondialog for no strong reason when new
# exit codes are added to the dialog-like program.
#
# As it is now, if such a thing happens, the program using
# pythondialog may receive an exit_code it doesn't know about. OK, the
# programmer just has to tell the pythondialog maintainer about it and
# can temporarily set the appropriate DIALOG_* environment variable if
# he wants and assign the corresponding value to the Dialog instance's
# DIALOG_FOO attribute from his program. He doesn't even need to use a
# patched pythondialog before he upgrades to a version that knows
# about the new exit codes.
#
# The bad thing that might happen is a new DIALOG_FOO exit code being
# the same by default as one of those we chose for the other exit
# codes already known by pythondialog. But in this situation, the
# check that is being discussed wouldn't help at all.
# Read dialog's output on its stderr
try:
child_output = os.fdopen(child_rfd, "rb").read()
# Now, since the file object has no reference anymore, the
# standard IO stream behind it will be closed, causing the
# end of the the pipe we used to read dialog's output on its
# stderr to be closed (this is important, otherwise invoking
# dialog enough times will eventually exhaust the maximum number
# of open file descriptors).
except IOError, v:
raise PythonDialogIOError(v)
return (exit_code, child_output)
def _perform(self, cmdargs, **kwargs):
"""Perform a complete dialog-like program invocation.
This function invokes the dialog-like program, waits for its
termination and returns its exit status and whatever it wrote
on its standard error stream.
Notable exceptions:
any exception raised by self._call_program() or
self._wait_for_program_termination()
"""
(child_pid, child_rfd) = \
self._call_program(False, *(cmdargs,), **kwargs)
(exit_code, output) = \
self._wait_for_program_termination(child_pid,
child_rfd)
return (exit_code, output)
def _strip_xdialog_newline(self, output):
"""Remove trailing newline (if any), if using Xdialog"""
if self.compat == "Xdialog" and output.endswith("\n"):
output = output[:-1]
return output
# This is for compatibility with the old dialog.py
def _perform_no_options(self, cmd):
"""Call dialog without passing any more options."""
return os.system(self._dialog_prg + ' ' + cmd)
# For compatibility with the old dialog.py
def clear(self):
"""Clear the screen. Equivalent to the dialog --clear option.
This method is obsolete. Please remove calls to it from your
programs.
"""
self._perform_no_options('--clear')
def form(self, text, height=20, width=50, form_height=20, fields=[], **kwargs):
"""Display a form dialog box.
text -- text to display in the box
height -- height of the box (minus the calendar height)
width -- width of the box
form_height -- height of the form
fields -- a list of tuples, each tuple has the form:
(label, item, len) or
(label, item, field_len, input_len)
it returns a tuple of the form (code, results), where results is a
list of the results.
Notable exceptions:
- any exception raised by self._perform()
- UnexpectedDialogOutput
- PythonDialogReModuleError
"""
cmd = ["--form", text, str(height), str(width), str(form_height)]
# find the longest label so we can put the input boxes at the
# correct offset
max_label_len = 0
for t in fields:
if len(t[0]) > max_label_len:
max_label_len = len(t[0]);
line = 1
for t in fields:
label = t[0]
item = t[1]
if item is None:
item = ""
field_len = str(t[2])
if len(t) < 4:
input_len = field_len
else:
input_len = str(t[3])
cmd.extend(((label, str(line), "1", item, str(line), str(max_label_len + 2), field_len, input_len)))
line += 1
(code, output) = self._perform(*(cmd,), **kwargs)
if output:
return (code, string.split(output, '\n')[:-1])
else: # empty selection
return (code, [])
def passwordform(self, text, height=20, width=50, form_height=20, fields=[], **kwargs):
"""Display a form dialog box.
text -- text to display in the box
height -- height of the box (minus the calendar height)
width -- width of the box
form_height -- height of the form
fields -- a list of tuples, each tuple has the form:
(label, item, len) or
(label, item, field_len, input_len)
it returns a tuple of the form (code, results), where results is a
list of the results.
Notable exceptions:
- any exception raised by self._perform()
- UnexpectedDialogOutput
- PythonDialogReModuleError
"""
cmd = ["--passwordform", text, str(height), str(width), str(form_height)]
# find the longest label so we can put the input boxes at the
# correct offset
max_label_len = 0
for t in fields:
if len(t[0]) > max_label_len:
max_label_len = len(t[0]);
line = 1
for t in fields:
label = t[0]
item = t[1]
field_len = str(t[2])
if len(t) < 4:
input_len = field_len
else:
input_len = str(t[3])
cmd.extend(((label, str(line), "1", item, str(line), str(max_label_len + 2), field_len, input_len)))
line += 1
# typing in password without stars is really awkward
kwargs["insecure"] = True
(code, output) = self._perform(*(cmd,), **kwargs)
if output:
return (code, string.split(output, '\n')[:-1])
else: # empty selection
return (code, [])
def calendar(self, text, height=6, width=0, day=0, month=0, year=0,
**kwargs):
"""Display a calendar dialog box.
text -- text to display in the box
height -- height of the box (minus the calendar height)
width -- width of the box
day -- inititial day highlighted
month -- inititial month displayed
year -- inititial year selected (0 causes the current date
to be used as the initial date)
A calendar box displays month, day and year in separately
adjustable windows. If the values for day, month or year are
missing or negative, the current date's corresponding values
are used. You can increment or decrement any of those using
the left, up, right and down arrows. Use tab or backtab to
move between windows. If the year is given as zero, the
current date is used as an initial value.
Return a tuple of the form (code, date) where `code' is the
exit status (an integer) of the dialog-like program and
`date' is a list of the form [day, month, year] (where `day',
`month' and `year' are integers corresponding to the date
chosen by the user) if the box was closed with OK, or None if
it was closed with the Cancel button.
Notable exceptions:
- any exception raised by self._perform()
- UnexpectedDialogOutput
- PythonDialogReModuleError
"""
(code, output) = self._perform(
*(["--calendar", text, str(height), str(width), str(day),
str(month), str(year)],),
**kwargs)
if code == self.DIALOG_OK:
try:
mo = _calendar_date_rec.match(output)
except re.error, v: