ATLAS Offline Software
Loading...
Searching...
No Matches
fprint.py
Go to the documentation of this file.
1# Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
2
35
36
37import string
38
39
41 """Format a value using py2 float formatting.
42
43>>> print (_formatFloat ('asd'))
44asd
45>>> print (_formatFloat (1.234567801234567))
461.23456780123
47>>> print (_formatFloat (2.0))
482.0
49>>> print (_formatFloat (2e30))
502e+30
51>>> print (_formatFloat (float('nan')))
52nan
53>>> print (_formatFloat (float('inf')))
54inf
55"""
56 # No change if it's not a float.
57 if not isinstance (x, float):
58 return x
59 # default formatting for floats in py2 was effectively the g format
60 # with 12 significant figures --- except that the g format removes
61 # a trailing `.0' while py2 preserves it.
62 s = '%.12g' % x
63 if s.find('.') < 0 and s.find('e') < 0 and s[-1] in string.digits:
64 return s + '.0'
65 return s
66
67
69 """Convert an argument list to use py2 formatting.
70>>> print (_formatFloats ((1, 'asd', 3.0)))
71(1, 'asd', '3.0')
72"""
73 return tuple ([_formatFloat(x) for x in l])
74
75
76def fprint (f, *args):
77 """Print a string with no terminating newline.
78
79Compatible with the python 2 print statement.
80
81>>> import sys
82>>> fprint (sys.stdout, 'a'); fprint (sys.stdout, 'b')
83a b
84>>> fwrite (sys.stdout, '\\n')
85<BLANKLINE>
86>>> fprint (sys.stdout, 'a'); fprint (sys.stdout, 2.0, '\\n'); fprint (sys.stdout, 'b')
87a 2.0
88b
89"""
90 if getattr (f, 'softspace', 0):
91 f.write (' ')
92 print (*_formatFloats (args), file=f, end='')
93 if len(args) > 0 and isinstance (args[-1], str) and args[-1].endswith('\n'):
94 f.softspace = 0
95 else:
96 f.softspace = 1
97 return
98
99
100def fprintln (f, *args):
101 """Print a string with a terminating newline.
102
103Compatible with the python 2 print statement.
104
105>>> import sys
106>>> sys.stdout.softspace = 0
107>>> fprint (sys.stdout, 'a'); fprintln (sys.stdout, 'b'); fprintln (sys.stdout, 'c'); fprint (sys.stdout, 'd')
108a b
109c
110d
111"""
112 if getattr (f, 'softspace', 0):
113 f.write (' ')
114 print (*_formatFloats(args), file=f)
115 f.softspace = 0
116 return
117
118
119def fwrite (f, *args):
120 """Write a string to a file.
121
122Compatible with the python 2 print statement space handling.
123>>> import sys
124>>> sys.stdout.softspace = 0
125>>> fprint (sys.stdout, 'a'); fwrite (sys.stdout, '\\n'); fprint (sys.stdout, 'c')
126a
127c
128"""
129 f.write (*args)
130 f.softspace = 0
131 return
132
133
134if __name__ == "__main__":
135 print ('PyUtils/fprint.py') #pragma: NO COVER
136 from PyUtils import coverage #pragma: NO COVER
137 c = coverage.Coverage ('PyUtils.fprint') #pragma: NO COVER
138 c.doctest_cover() #pragma: NO COVER
fprintln(f, *args)
Definition fprint.py:100
fwrite(f, *args)
Definition fprint.py:119
_formatFloats(l)
Definition fprint.py:68
_formatFloat(x)
Definition fprint.py:40