Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/utils/io.py: 25%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

60 statements  

1""" 

2IO related utilities. 

3""" 

4 

5# Copyright (c) IPython Development Team. 

6# Distributed under the terms of the Modified BSD License. 

7 

8 

9 

10import sys 

11import tempfile 

12from pathlib import Path 

13 

14from .capture import CapturedIO, capture_output 

15from io import StringIO 

16 

17 

18class Tee: 

19 """A class to duplicate an output stream to stdout/err. 

20 

21 This works in a manner very similar to the Unix 'tee' command. 

22 

23 When the object is closed or deleted, it closes the original file given to 

24 it for duplication. 

25 """ 

26 # Inspired by: 

27 # http://mail.python.org/pipermail/python-list/2007-May/442737.html 

28 

29 def __init__(self, file_or_name: str | StringIO, mode: str="w", channel: str='stdout'): 

30 """Construct a new Tee object. 

31 

32 Parameters 

33 ---------- 

34 file_or_name : filename or open filehandle (writable) 

35 File that will be duplicated 

36 mode : optional, valid mode for open(). 

37 If a filename was give, open with this mode. 

38 channel : str, one of ['stdout', 'stderr'] 

39 """ 

40 self._closed = True 

41 if channel not in ['stdout', 'stderr']: 

42 raise ValueError('Invalid channel spec %s' % channel) 

43 

44 if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'): 

45 self.file = file_or_name 

46 else: 

47 encoding = None if "b" in mode else "utf-8" 

48 self.file = open(file_or_name, mode, encoding=encoding) 

49 self.channel = channel 

50 self.ostream = getattr(sys, channel) 

51 setattr(sys, channel, self) 

52 self._closed = False # fully initialized, mark as open 

53 

54 def close(self): 

55 """Close the file and restore the channel.""" 

56 self.flush() 

57 setattr(sys, self.channel, self.ostream) 

58 self.file.close() 

59 self._closed = True 

60 

61 def write(self, data): 

62 """Write data to both channels.""" 

63 self.file.write(data) 

64 self.ostream.write(data) 

65 self.ostream.flush() 

66 

67 def flush(self): 

68 """Flush both channels.""" 

69 self.file.flush() 

70 self.ostream.flush() 

71 

72 def __del__(self): 

73 if not self._closed: 

74 self.close() 

75 

76 def isatty(self): 

77 return False 

78 

79def ask_yes_no(prompt, default=None, interrupt=None): 

80 """Asks a question and returns a boolean (y/n) answer. 

81 

82 If default is given (one of 'y','n'), it is used if the user input is 

83 empty. If interrupt is given (one of 'y','n'), it is used if the user 

84 presses Ctrl-C. Otherwise the question is repeated until an answer is 

85 given. 

86 

87 An EOF is treated as the default answer. If there is no default, an 

88 exception is raised to prevent infinite loops. 

89 

90 Valid answers are: y/yes/n/no (match is not case sensitive).""" 

91 

92 answers = {'y':True,'n':False,'yes':True,'no':False} 

93 ans = None 

94 while ans not in answers.keys(): 

95 try: 

96 ans = input(prompt+' ').lower() 

97 if not ans: # response was an empty string 

98 ans = default 

99 except KeyboardInterrupt: 

100 if interrupt: 

101 ans = interrupt 

102 print("\r") 

103 except EOFError: 

104 if default in answers.keys(): 

105 ans = default 

106 print() 

107 else: 

108 raise 

109 

110 return answers[ans] 

111 

112 

113def temp_pyfile(src: str, ext: str='.py') -> str: 

114 """Make a temporary python file, return filename and filehandle. 

115 

116 Parameters 

117 ---------- 

118 src : string or list of strings (no need for ending newlines if list) 

119 Source code to be written to the file. 

120 ext : optional, string 

121 Extension for the generated file. 

122 

123 Returns 

124 ------- 

125 (filename, open filehandle) 

126 It is the caller's responsibility to close the open file and unlink it. 

127 """ 

128 fname = tempfile.mkstemp(ext)[1] 

129 with open(Path(fname), "w", encoding="utf-8") as f: 

130 f.write(src) 

131 f.flush() 

132 return fname