Skip to content

Commit 9afc4c5

Browse files
committed
python3 portability
1 parent cfba7f9 commit 9afc4c5

File tree

7 files changed

+34
-35
lines changed

7 files changed

+34
-35
lines changed

pystatsd/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from statsd import Client
2-
from server import Server
1+
from .statsd import Client
2+
from .server import Server
33

44
VERSION = (0, 1, 10)

pystatsd/daemon.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
Based on http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
44
"""
55

6-
from __future__ import with_statement
7-
86
import atexit
97
import os
108
from signal import SIGTERM
@@ -27,23 +25,23 @@ def daemonize(self):
2725
if pid > 0:
2826
# First parent; exit.
2927
sys.exit(0)
30-
except OSError, e:
28+
except OSError as e:
3129
sys.stderr.write('Could not fork! %d (%s)\n' %
3230
(e.errno, e.strerror))
3331
sys.exit(1)
3432

3533
# Disconnect from parent environment.
3634
os.chdir('/')
3735
os.setsid()
38-
os.umask(0022)
36+
os.umask(0o022)
3937

4038
# Fork again.
4139
try:
4240
pid = os.fork()
4341
if pid > 0:
4442
# Second parent; exit.
4543
sys.exit(0)
46-
except OSError, e:
44+
except OSError as e:
4745
sys.stderr.write('Could not fork (2nd)! %d (%s)\n' %
4846
(e.errno, e.strerror))
4947
sys.exit(1)
@@ -98,13 +96,13 @@ def stop(self):
9896
while 1:
9997
os.kill(pid, SIGTERM)
10098
time.sleep(0.1)
101-
except OSError, e:
99+
except OSError as e:
102100
e = str(e)
103101
if e.find('No such process') > 0:
104102
if os.path.exists(self.pidfile):
105103
os.remove(self.pidfile)
106104
else:
107-
print e
105+
print(e)
108106
sys.exit(1)
109107

110108
def restart(self, *args, **kw):

pystatsd/gmetric.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __init__(self, host, port, protocol):
8181
def send(self, NAME, VAL, TYPE='', UNITS='', SLOPE='both',
8282
TMAX=60, DMAX=0, GROUP="", SPOOF=""):
8383
if SLOPE not in slope_str2int:
84-
raise ValueError("Slope must be one of: " + str(self.slope.keys()))
84+
raise ValueError("Slope must be one of: " + str(list(self.slope.keys())))
8585
if TYPE not in self.type:
8686
raise ValueError("Type must be one of: " + str(self.type))
8787
if len(NAME) == 0:
@@ -90,8 +90,8 @@ def send(self, NAME, VAL, TYPE='', UNITS='', SLOPE='both',
9090
( meta_msg, data_msg ) = gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF)
9191
# print msg
9292

93-
self.socket.sendto(meta_msg, self.hostport)
94-
self.socket.sendto(data_msg, self.hostport)
93+
self.socket.sendto(bytes(bytearray(meta_msg, "utf-8")), self.hostport)
94+
self.socket.sendto(bytes(bytearray(data_msg, "utf-8")), self.hostport)
9595

9696
def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF):
9797
"""
@@ -185,4 +185,4 @@ def gmetric_read(msg):
185185

186186
g = Gmetric(options.host, options.port, options.protocol)
187187
g.send(options.name, options.value, options.type, options.units,
188-
options.slope, options.tmax, options.dmax, options.group, options.spoof)
188+
options.slope, options.tmax, options.dmax, options.group, options.spoof)

pystatsd/server.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import time
55
import types
66
import logging
7-
import gmetric
7+
from . import gmetric
88
from subprocess import call
99
from warnings import warn
1010
# from xdrlib import Packer, Unpacker
@@ -16,7 +16,7 @@
1616
except ImportError:
1717
setproctitle = None
1818

19-
from daemon import Daemon
19+
from .daemon import Daemon
2020

2121

2222
__all__ = ['Server']
@@ -141,7 +141,7 @@ def on_timer(self):
141141
"""
142142
try:
143143
self.flush()
144-
except Exception, e:
144+
except Exception as e:
145145
log.exception('Error while flushing: %s', e)
146146
self._set_timer()
147147

@@ -157,14 +157,14 @@ def flush(self):
157157
for k, (v, t) in self.counters.items():
158158
if self.expire > 0 and t + self.expire < ts:
159159
if self.debug:
160-
print "Expiring counter %s (age: %s)" % (k, ts -t)
160+
print("Expiring counter %s (age: %s)" % (k, ts -t))
161161
del(self.counters[k])
162162
continue
163163
v = float(v)
164164
v = v if self.no_aggregate_counters else v / (self.flush_interval / 1000)
165165

166166
if self.debug:
167-
print "Sending %s => count=%s" % (k, v)
167+
print("Sending %s => count=%s" % (k, v))
168168

169169
if self.transport == 'graphite':
170170
msg = '%s.%s %s %s\n' % (self.counters_prefix, k, v, ts)
@@ -183,13 +183,13 @@ def flush(self):
183183
for k, (v, t) in self.gauges.items():
184184
if self.expire > 0 and t + self.expire < ts:
185185
if self.debug:
186-
print "Expiring gauge %s (age: %s)" % (k, ts - t)
186+
print("Expiring gauge %s (age: %s)" % (k, ts - t))
187187
del(self.gauges[k])
188188
continue
189189
v = float(v)
190190

191191
if self.debug:
192-
print "Sending %s => value=%s" % (k, v)
192+
print("Sending %s => value=%s" % (k, v))
193193

194194
if self.transport == 'graphite':
195195
# note: counters and gauges implicitly end up in the same namespace
@@ -205,7 +205,7 @@ def flush(self):
205205
for k, (v, t) in self.timers.items():
206206
if self.expire > 0 and t + self.expire < ts:
207207
if self.debug:
208-
print "Expiring timer %s (age: %s)" % (k, ts - t)
208+
print("Expiring timer %s (age: %s)" % (k, ts - t))
209209
del(self.timers[k])
210210
continue
211211
if len(v) > 0:
@@ -227,8 +227,8 @@ def flush(self):
227227
del(self.timers[k])
228228

229229
if self.debug:
230-
print "Sending %s ====> lower=%s, mean=%s, upper=%s, %dpct=%s, count=%s" \
231-
% (k, min, mean, max, self.pct_threshold, max_threshold, count)
230+
print("Sending %s ====> lower=%s, mean=%s, upper=%s, %dpct=%s, count=%s" \
231+
% (k, min, mean, max, self.pct_threshold, max_threshold, count))
232232

233233
if self.transport == 'graphite':
234234

@@ -272,24 +272,24 @@ def flush(self):
272272
graphite = socket.socket()
273273
try:
274274
graphite.connect((self.graphite_host, self.graphite_port))
275-
graphite.sendall(stat_string)
275+
graphite.sendall(bytes(bytearray(stat_string, "utf-8")))
276276
graphite.close()
277-
except socket.error, e:
277+
except socket.error as e:
278278
log.error("Error communicating with Graphite: %s" % e)
279279
if self.debug:
280-
print "Error communicating with Graphite: %s" % e
280+
print("Error communicating with Graphite: %s" % e)
281281

282282
if self.debug:
283-
print "\n================== Flush completed. Waiting until next flush. Sent out %d metrics =======" \
284-
% (stats)
283+
print("\n================== Flush completed. Waiting until next flush. Sent out %d metrics =======" \
284+
% (stats))
285285

286286
def _set_timer(self):
287287
self._timer = threading.Timer(self.flush_interval / 1000, self.on_timer)
288288
self._timer.daemon = True
289289
self._timer.start()
290290

291291
def serve(self, hostname='', port=8125):
292-
assert type(port) is types.IntType, 'port is not an integer: %s' % (port)
292+
assert type(port) is int, 'port is not an integer: %s' % (port)
293293
addr = (hostname, port)
294294
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
295295
self._sock.bind(addr)

pystatsd/statsd.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def __init__(self, host='localhost', port=8125, prefix=None):
2626
self.addr = (socket.gethostbyname(self.host), self.port)
2727
self.prefix = prefix
2828
self.log = logging.getLogger("pystatsd.client")
29+
self.log.addHandler(logging.StreamHandler())
2930
self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
3031

3132
def timing_since(self, stat, start, sample_rate=1):
@@ -91,17 +92,17 @@ def send(self, data, sample_rate=1):
9192
"""
9293

9394
if self.prefix:
94-
data = dict((".".join((self.prefix, stat)), value) for stat, value in data.iteritems())
95+
data = dict((".".join((self.prefix, stat)), value) for stat, value in data.items())
9596

9697
if sample_rate < 1:
9798
if random.random() > sample_rate:
9899
return
99-
sampled_data = dict((stat, "%s|@%s" % (value, sample_rate)) for stat, value in data.iteritems())
100+
sampled_data = dict((stat, "%s|@%s" % (value, sample_rate)) for stat, value in data.items())
100101
else:
101102
sampled_data = data
102103

103104
try:
104-
[self.udp_sock.sendto("%s:%s" % (stat, value), self.addr) for stat, value in sampled_data.iteritems()]
105+
[self.udp_sock.sendto(bytes(bytearray("%s:%s" % (stat, value), "utf-8")), self.addr) for stat, value in sampled_data.items()]
105106
except:
106107
self.log.exception("unexpected error")
107108

tests/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
from client import *
2-
from server import *
1+
from .client import *
2+
from .server import *

tests/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def test_basic_client_update_stats_multi(self):
7272

7373
self.client.update_stats(stats, 5)
7474

75-
for stat, value in data.iteritems():
75+
for stat, value in data.items():
7676
stat_str = stat + value
7777
# thanks tos9 in #python for 'splaining the return_value bit.
7878
self.mock_socket.return_value.sendto.assert_call_any(

0 commit comments

Comments
 (0)