Commit 78ccc6ef authored by Leo Pound Singer's avatar Leo Pound Singer
Browse files

python3: port with help of python-modernize

parent 3da71418
......@@ -16,6 +16,7 @@
# You should have received a copy of the GNU General Public License
# along with lvalert. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import netrc
import sys
import os
......@@ -142,7 +143,7 @@ opts, args = parser.parse_args()
if opts.version:
import pkg_resources
version = pkg_resources.require("ligo-lvalert")[0].version
print "LVAlert v. %s" % version
print("LVAlert v. %s" % version)
exit(0)
if (opts.add_publisher or opts.create or opts.delete or opts.subscribe or opts.unsubscribe or opts.delete_publisher) and not opts.node:
......@@ -183,7 +184,7 @@ class MyClient(Client):
component to a server changes. This will usually be used to
let the user know what is going on."""
if opts.verbose:
print "*** State changed: %s %r ***" % (state,arg)
print("*** State changed: %s %r ***" % (state,arg))
else:
pass
......@@ -230,14 +231,14 @@ class MyClient(Client):
def idle(self):
if self.stream and self.session_established:
if opts.verbose:
print "Disconnecting"
print("Disconnecting")
self.disconnect()
if opts.verbose:
print "idle"
print("idle")
time.sleep(4)
def post_disconnect(self):
print "Disconnected"
print("Disconnected")
raise Disconnected
......@@ -258,19 +259,19 @@ myjid=JID(myusername+"@"+opts.server+"/"+opts.resource+uuid.uuid4().hex)
s=MyClient(jid=myjid,password=mypassword)
if opts.verbose:
print "connecting..."
print("connecting...")
s.connect()
if opts.verbose:
print "build pubsub stanza..."
print("build pubsub stanza...")
recpt=JID("pubsub."+opts.server)
pspl=pubsub.PubSub(from_jid = myjid, to_jid = recpt, stream = s,\
stanza_type="get")
if opts.get_nodes:
print "Getting nodes"
print("Getting nodes")
pspl.get_nodes()
elif opts.create:
print "Creating node " + opts.node
print("Creating node " + opts.node)
pspl.create_node(opts.node)
elif opts.delete:
pspl.delete_node(opts.node)
......@@ -294,12 +295,12 @@ else:
pspl.get_nodes()
if opts.verbose:
print "sending message..."
print("sending message...")
try:
s.loop(1)
except KeyboardInterrupt:
print u"disconnecting..."
print(u"disconnecting...")
s.disconnect()
# vi: sts=4 et sw=4
......@@ -17,6 +17,7 @@
# You should have received a copy of the GNU General Public License
# along with lvalert. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import netrc
import sys
import os
......@@ -27,7 +28,7 @@ import logging
import libxml2
import getpass
import uuid
import ConfigParser
import six.moves.configparser
from subprocess import Popen, PIPE
from optparse import *
from M2Crypto.SSL import Context
......@@ -158,7 +159,7 @@ opts, args = parser.parse_args()
if opts.version:
import pkg_resources
version = pkg_resources.require("ligo-lvalert")[0].version
print "LVAlert v. %s" % version
print("LVAlert v. %s" % version)
exit(0)
try:
......@@ -241,7 +242,7 @@ class LVAlertHandler(object):
### max_size=1000 (bytes?) should be larger than most expected lvalert messages?
elif self.wait:
p = Popen([self.actions[n]], stdin=PIPE, stdout=PIPE)
print p.communicate(e)[0]
print(p.communicate(e)[0])
else:
# import tempfile
file_obj = tempfile.SpooledTemporaryFile(mode="w+r", max_size=1000)
......@@ -258,9 +259,9 @@ class LVAlertHandler(object):
#===================================================================
sys.stdout.flush()
else:
print "Payload received at %s" % (datetime.datetime.now().ctime())
print("Payload received at %s" % (datetime.datetime.now().ctime()))
if opts.show:
print u'%s' % (e,),
print(u'%s' % (e,), end=' ')
return True
def get_node(self,stanza):
......@@ -306,7 +307,7 @@ class MyClient(Client):
component to a server changes. This will usually be used to
let the user know what is going on."""
if opts.verbose:
print "*** State changed: %s %r ***" % (state,arg)
print("*** State changed: %s %r ***" % (state,arg))
else:
pass
......@@ -324,12 +325,12 @@ libxml2.debugMemory(1)
# set up handlers for each node
actions={}
if opts.config_file:
cp=ConfigParser.ConfigParser()
cp=six.moves.configparser.ConfigParser()
cp.read(opts.config_file)
for node in cp.sections():
try:
actions[node] = cp.get(node,'executible')
except ConfigParser.NoOptionError:
except six.moves.configparser.NoOptionError:
actions[node] = cp.get(node,'executable')
# set up the stream
......@@ -338,15 +339,15 @@ myjid=JID(myusername+"@"+opts.server+"/"+opts.resource+uuid.uuid4().hex)
s=MyClient(myjid,mypassword,actions, wait=not opts.dont_wait)
if opts.verbose:
print "connecting..."
print("connecting...")
s.connect()
if opts.verbose:
print "listening for message..."
print("listening for message...")
try:
s.loop(1)
except KeyboardInterrupt:
print u"disconnecting..."
print(u"disconnecting...")
s.disconnect()
# vi: sts=4 et sw=4
......@@ -16,6 +16,7 @@
# You should have received a copy of the GNU General Public License
# along with lvalert. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import netrc
import sys
import os
......@@ -121,7 +122,7 @@ opts, args = parser.parse_args()
if opts.version:
import pkg_resources
version = pkg_resources.require("ligo-lvalert")[0].version
print "LVAlert v. %s" % version
print("LVAlert v. %s" % version)
exit(0)
try:
......@@ -138,10 +139,10 @@ else:
mypassword = getpass.getpass('password for ' + myusername + ': ')
if not opts.node:
raise ValueError, "--node is required"
raise ValueError("--node is required")
if not opts.file:
raise ValueError, "--file is required"
raise ValueError("--file is required")
# add a logger so that we can see what's going
logger=logging.getLogger(__name__)
......@@ -230,14 +231,14 @@ class MyClient(Client):
self.counter = self.counter + 1
self.sendMessage(node,msg,recpt)
else:
print "Reached max_attempts. Disconnecting..."
print("Reached max_attempts. Disconnecting...")
self.disconnect()
sys.exit(1)
return True
# Check for file
if not opts.file:
print "You must supply a file to send"
print("You must supply a file to send")
sys.exit(1)
# Debug the memory
......@@ -255,7 +256,7 @@ client.connect()
try:
client.loop(1)
except KeyboardInterrupt:
print u"disconnecting..."
print("disconnecting...")
client.disconnect()
# vi: sts=4 et sw=4
......@@ -113,10 +113,10 @@ class LVAlertStanzaProcessor(LVAlertSP):
ufr=fr.as_unicode()
else:
ufr=None
if self._iq_response_handlers.has_key((sid,ufr)):
if (sid,ufr) in self._iq_response_handlers:
key=(sid,ufr)
elif ( (fr==self.peer or fr==self.me)
and self._iq_response_handlers.has_key((sid,None))):
and (sid,None) in self._iq_response_handlers):
key=(sid,None)
else:
return False
......@@ -131,26 +131,26 @@ class LVAlertStanzaProcessor(LVAlertSP):
q=stanza.get_query()
if not q:
raise BadRequestProtocolError, "Stanza with no child element"
raise BadRequestProtocolError("Stanza with no child element")
el=q.name
ns=q.ns().getContent()
if typ=="get":
if self._iq_get_handlers.has_key((el,ns)):
if (el,ns) in self._iq_get_handlers:
response = self._iq_get_handlers[(el,ns)](stanza)
self.process_response(response)
return True
else:
raise FeatureNotImplementedProtocolError, "Not implemented"
raise FeatureNotImplementedProtocolError("Not implemented")
elif typ=="set":
if self._iq_set_handlers.has_key((el,ns)):
if (el,ns) in self._iq_set_handlers:
response = self._iq_set_handlers[(el,ns)](stanza)
self.process_response(response)
return True
else:
raise FeatureNotImplementedProtocolError, "Not implemented"
raise FeatureNotImplementedProtocolError("Not implemented")
else:
raise BadRequestProtocolError, "Unknown IQ stanza type"
raise BadRequestProtocolError("Unknown IQ stanza type")
def __try_handlers(self,handler_list,typ,stanza):
""" Search the handler list for handlers matching
......@@ -286,7 +286,7 @@ class LVAlertStanzaProcessor(LVAlertSP):
elif stanza.stanza_type=="presence":
if self.process_presence(stanza):
return True
except ProtocolError, e:
except ProtocolError as e:
typ = stanza.get_type()
if typ != 'error' and (typ != 'result' or stanza.stanza_type != 'iq'):
r = stanza.make_error_response(e.xmpp_name)
......@@ -384,7 +384,7 @@ class LVAlertStanzaProcessor(LVAlertSP):
"""
self.lock.acquire()
try:
if self._iq_get_handlers.has_key((element,namespace)):
if (element,namespace) in self._iq_get_handlers:
del self._iq_get_handlers[(element,namespace)]
finally:
self.lock.release()
......@@ -418,7 +418,7 @@ class LVAlertStanzaProcessor(LVAlertSP):
- `namespace`: payload element namespace URI."""
self.lock.acquire()
try:
if self._iq_set_handlers.has_key((element,namespace)):
if (element,namespace) in self._iq_set_handlers:
del self._iq_set_handlers[(element,namespace)]
finally:
self.lock.release()
......@@ -433,7 +433,7 @@ class LVAlertStanzaProcessor(LVAlertSP):
- `priority`: handler priority. Must be >=0 and <=100. Handlers
with lower priority list will be tried first."""
if priority<0 or priority>100:
raise ValueError,"Bad handler priority (must be in 0:100)"
raise ValueError("Bad handler priority (must be in 0:100)")
handler_list.append((priority,typ,namespace,handler))
handler_list.sort()
......@@ -516,7 +516,7 @@ class LVAlertStanzaProcessor(LVAlertSP):
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
raise NotImplementedError,"This method must be overriden in derived classes."""
raise NotImplementedError("This method must be overriden in derived classes.""")
pyxmpp.stanzaprocessor.StanzaProcessor = LVAlertStanzaProcessor
......
......@@ -24,6 +24,7 @@ Normative reference:
????
"""
from __future__ import print_function
__revision__="$Id$"
__docformat__="restructuredtext en"
......@@ -96,9 +97,9 @@ class PubSub(Iq):
def get_nodes_result(self,cresult):
c = cresult.xmlnode.children
c = c.children
print "List of nodes"
print("List of nodes")
while c:
print "Node: %s, %s" % (c.prop("node"), c.prop("name"))
print("Node: %s, %s" % (c.prop("node"), c.prop("name")))
c = c.next
#print "End list of nodes"
......@@ -111,7 +112,7 @@ class PubSub(Iq):
self.set_type("set")
def generic_result(self,cresult):
print "Successfully completed operation"
print("Successfully completed operation")
def create_timeout(self,ctimeout):
"""Process session request time out.
......@@ -155,8 +156,8 @@ class PubSub(Iq):
def subscriptions_result(self,cresult):
c = cresult.xmlnode.children.children.children
while c:
print "Node: %s [ %s subid=%s]" % ( c.prop("node"),\
c.prop("subscription"), c.prop("subid") )
print("Node: %s [ %s subid=%s]" % ( c.prop("node"),\
c.prop("subscription"), c.prop("subid") ))
c = c.next
def publisher(self,jid,node_name,affiliation):
......@@ -179,8 +180,8 @@ class PubSub(Iq):
def affiliations_result(self,cresult):
c = cresult.xmlnode.children.children.children
while c:
print "Affiliation: %s [ %s ]" % ( c.prop("jid"),\
c.prop("affiliation"))
print("Affiliation: %s [ %s ]" % ( c.prop("jid"),\
c.prop("affiliation")))
c = c.next
def subscribe(self,jid,node_name):
......@@ -204,7 +205,7 @@ class PubSub(Iq):
def subscribe_result(self,cresult):
node_name = cresult.get_query().children.prop("node")
print "Successfully subscribed to node %s" % node_name
print("Successfully subscribed to node %s" % node_name)
def subscribe_timeout(self,ctimeout):
"""Process session request time out.
......@@ -246,11 +247,11 @@ class PubSubMessage(Stanza):
if isinstance(xmlnode,PubSubMessage):
pass
elif isinstance(xmlnode,Stanza):
raise TypeError, "Couldn't make PubSubMessage from other Stanza"
raise TypeError("Couldn't make PubSubMessage from other Stanza")
elif isinstance(xmlnode,libxml2.xmlNode):
pass
elif xmlnode is not None:
raise TypeError, "Couldn't make PubSubMessage from %r" % (type(xmlnode),)
raise TypeError("Couldn't make PubSubMessage from %r" % (type(xmlnode),))
if xmlnode is None:
xmlnode="message"
......
......@@ -18,7 +18,8 @@
import sys
import os
import urlparse
from six.moves.urllib.parse import urlparse
from six import StringIO
from optparse import *
from subprocess import Popen,PIPE
......@@ -26,7 +27,6 @@ from subprocess import Popen,PIPE
import warnings
import json
import StringIO
try:
from glue.ligolw import ligolw
......@@ -66,7 +66,7 @@ class LVAlertTable(Table):
}
class LVAlertRow(object):
__slots__ = LVAlertTable.validcolumns.keys()
__slots__ = list(LVAlertTable.validcolumns.keys())
LVAlertTable.RowType = LVAlertRow
......@@ -87,7 +87,7 @@ def parse_file_url(file_url):
general_dir: the /general subdir of the gracedb entry (where data not
produced by the event supplier should be placed)
"""
parsed = urlparse.urlparse(file_url)
parsed = urlparse(file_url)
host = parsed[1]
path, fname = os.path.split(parsed[2])
......@@ -114,10 +114,10 @@ def get_LVAdata_from_stdin(std_in, as_dict=False):
data_loc = out_dict['data_loc']
description = out_dict['description']
alert_type = out_dict['alert_type']
except Exception, e:
except Exception as e:
# We don't have a file object anymore, because we .read() it.
# Instead, we want this to load a blob of text.
f = StringIO.StringIO(content)
f = StringIO(content)
doc = utils.load_fileobj(f, contenthandler = LIGOLWContentHandler)[0]
lvatable = table.get_table(doc, LVAlertTable.tableName)
file = lvatable[0].file
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment