I got this error in my program:
Traceback (most recent call last):
File "scriptA.py", line 17, in <module>
socketPub.bind("tcp://localhost:%s"% portPub)
File "socket.pyx", line 434, in zmq.backend.cython.socket.Socket.bind (zmq/backend/cython/socket.c:3928)
File "checkrc.pxd", line 21, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:6058)
zmq.error.ZMQError: No such device
This is a simple script I have done to reproduce it:
import zmq
import random
import sys
import time
port = "5566"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
portSub = "5556"
context = zmq.Context()
portPub = "5566"
#contextPub = zmq.Context()
socketPub = context.socket(zmq.PUB)
socketPub.bind("tcp://localhost:%s"% portPub)
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:%s"% portSub)
socket.setsockopt(zmq.SUBSCRIBE,'')
while True:
socket.send("BB", zmq.SNDMORE)
socket.send("16", zmq.SNDMORE)
socket.send("14", zmq.SNDMORE)
socket.send("11", zmq.SNDMORE)
socket.send("4")
time.sleep(3)
I want to subscribe to one point and be able to send to another one. Is it possible? 2 differents end points. A sends to B and B sends to C.
Try to replace localhost by 127.0.0.1.
For more information, have a look at this stackoverflow thread
Your port numbers do not match. From your code:
portSub = "5556"
portPub = "5566"
So you are binding to one port and connecting to another. Make sure the ports match or simply do:
portSub = "5556"
portPub = portSub
Furthermore, I'm not sure if your binding-string "tcp://localhost:%s"% portPub is correct. When working with ZMQ, I always use the Asterisk * instead of localhost or 127.0.0.1. This always works for me and is something you can try if changing the port number does not make it work: "tcp://*:%s"% portPub (or I prefer f'tcp://*:{portPub}', which is more readable I think). I think you have to use the binding-string I propose. Your connection-string seems to be fine.
Related
Here is my python code that I am using. I am trying to use a wii remote to trigger a buzzer. I thought this would be an interesting use for my old wii remote. The code that interacts with the buzzer works fine because I used an example script to test it. However, when I try and run it I keep getting this one error (see bottom). I am new to python and would appreciate any help.
import cwiid
from gpiozero import LED
import time
import os
Buzzer1 = LED(17)
Buzzer2 = LED(27)
def ConnectRemote():
os.system("rfkill unblock bluetooth")
print 'Press 1+2 On The Remote...'
global wm
wm = wiid.Wiimote()
print 'Connection Established!\n'
wm.led = 1
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
time.sleep(0.5)
wm.rpt_mode = cwiid.RPT_BTN
def TryToConnect():
while True:
ConnectRemote()
break
while True:
buttons = wm.state['buttons']
#shutdown function using plus and minus buttons
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing Connection To Wiimote'
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
os.system("rfkill block bluetooth")
TryToConnect()
if (buttons & cwiid.BTN_A):
print 'Buzzer On'
Buzzer1.on()
Buzzer2.on()
else:
Buzzer1.off()
Buzzer2.off()
and yet I keep getting an error of
Traceback (most recent call last):
File "WiimoteLEDs.py", line 36, in <module>
buttons = wm.state['buttons']
NameError: global name 'wm' is not defined
Can anyone help? Thanks in advance
I think you should initialized variable wm before using this variable in function.
This bug is related to 'Global name not defined'
I am newbie to python. I am trying to connect to my IBM MQ and put some messages in them through the Python code.
import pymqi
queue_manager = 'XXXXXX'
channel = 'XXXXX'
host = 'XXXXX'
port = 'XXXX'
conn_info = '%s(%s)' % (host, port)
qmgr = pymqi.connect(queue_manager, channel, conn_info)
file = open('E:\D Drive Back up\Scripts\Data1.csv','r')
y = file.readlines()
print y[1]
putQ = pymqi.Queue(qmgr, queue_manager)
putQ.put(y[1])
qmgr.disconnect()
Sample Data which I am trying to input:
{1:F01COBADEFFGXXX3575743055}{2:I103BARCGB22GXXXU3003}{4:##:20:Forw092010004R1##:23B:CRED##:32A:181010EUR250000,00##:50F:/N101000004EUR##1/John Doe##2/Dankelmannstrasse 6##3/DE/Berlin##:59F:/N101000004EUR##1/Jane Doe##2/Wissmannstr 1##3/DE/Berlin##:71A:BEN##-}{5:{MAC:11111111}{CHK:6E470F24FDE6}}
The output I am getting is this:
E:\D Drive Back up\Scripts>python MQ.py
{1:F01COBADEFFGXXX3575743055}{2:I103BARCGB22GXXXU3003}{4:##:20:Forw092010R1##:23B:CRED##:32A:181010EUR1000000,00##:50F:/N101000004EUR##1/John Doe##2/Dankelmannstrasse 6##3/DE/Berlin##:59F:/N101000004EUR##1/Jane Doe##2/Wissmannstr 1##3/DE/Berlin##:71A:BEN##-}{5:{MAC:11111111}{CHK:6E470F24FDE6}}
Traceback (most recent call last):
File "MQ.py", line 19, in
putQ.put(y[1])
File "C:\Users\aassharma\AppData\Local\Continuum\anaconda2\lib\site-packages\pymqi_init_.py", line 1727, in put
self._realOpen()
File "C:\Users\aassharma\AppData\Local\Continuum\anaconda2\lib\site-packages\pymqi_init.py", line 1632, in __realOpen
raise MQMIError(rv[-2], rv[-1])
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2085: FAILED: MQRC_UNKNOWN_OBJECT_NAME
Compare your code to the pymqi put sample from - https://dsuch.github.io/pymqi/examples.html#how-to-put-the-message-on-a-queue
import pymqi
queue_manager = 'QM1'
channel = 'DEV.APP.SVRCONN'
host = '127.0.0.1'
port = '1414'
queue_name = 'TEST.1'
message = 'Hello from Python!'
conn_info = '%s(%s)' % (host, port)
qmgr = pymqi.connect(queue_manager, channel, conn_info)
queue = pymqi.Queue(qmgr, queue_name)
queue.put(message)
queue.close()
qmgr.disconnect()
As Morag Hughson and JoshMc already pointed out, the difference is queue_name. You don't specify one.
It should be something like 'DEV.QUEUE.1' and used as the second parameter in the call to connect to the queue - queue = pymqi.Queue(qmgr, queue_name). You pass in the Queue Manager, which I guess will be something like 'QM1', which is very unlikely to be the queue name on your MQ Server, and also why you are getting the error MQRC_UNKNOWN_OBJECT_NAME.
I am using grpc with protobuf 2.6.1 in python 2.7, and when I run my client side code, I have the following errors:
Traceback (most recent call last):
File "debate_client.py", line 31, in <module>
run_client()
File "debate_client.py", line 17, in run_client
reply = stub.Answer(debate_pb2.AnswerRequest(question=question, timeout=timeout), 30)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/implementations.py", line 73, in __call__
protocol_options, metadata, request)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/_calls.py", line 109, in blocking_unary_unary
return next(rendezvous)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/_control.py", line 412, in next
raise self._termination.abortion_error
grpc.framework.interfaces.face.face.RemoteError: RemoteError(code=StatusCode.UNKNOWN, details="")
Here is my client side code:
from grpc.beta import implementations
import debate_pb2
import sys
def run_client():
params = sys.argv
print params
how = params[1]
question = params[2]
channel = implementations.insecure_channel('localhost', 29999)
stub = debate_pb2.beta_create_Candidate_stub(channel)
if how.lower() == "answer":
timeout = int(params[3])
reply = stub.Answer(debate_pb2.AnswerRequest(question=question, timeout=timeout), 30)
elif how.lower() == "elaborate":
blah = params[3:len(sys.argv)]
for i in range(0, len(blah)):
blah[i] = int(blah[i])
reply = stub.Elaborate(debate_pb2.ElaborateRequest(topic=question, blah_run=blah), 30)
if reply is None:
print "No comment"
else:
print reply.answer
if __name__ == "__main__":
run_client()
And here is my server side code:
import debate_pb2
import consultation_pb2
import re
import random
from grpc.beta import implementations
class Debate(debate_pb2.BetaCandidateServicer):
def Answer(self, request, context=None):
#Answer implementation
def Elaborate(self, request, context=None):
#Elaborate implementation
def run_server():
server = debate_pb2.beta_create_Candidate_server(Debate())
server.add_insecure_port('localhost:29999')
server.start()
if __name__ == "__main__":
run_server()
Any idea where the remote error comes from? Thank you so much!
Hello Elaine and thank you for trying out gRPC Python.
Nothing leaps out at me as an obvious smoking gun, but a couple of things I see are:
gRPC Python isn't known to work with protobuf 2.6.1. Have you tried working with the very latest protobuf release (3.0.0a3 at this time)?
context isn't an optional keyword parameter in servicer methods; it's a required, positional parameter. Does dropping =None from your servicer method implementations effect any change?
The same happened to me just now, and I figured out why.
Make sure the messages in your proto definition and the message in your implementations match the format.
For example, my Response message had a message= param in my python server, but not in my proto definition.
I think your function implementations should be outside class Debate or might be your functions are not correctly implemented to give the desired result.
I faced a similar error because my functions were inside the class but moving it outside the class fixed it.
I have a tool, where i am implementing upnp discovery of devices connected in network.
For that i have written a script and used datagram class in it.
Implementation:
whenever scan button is pressed on tool, it will run that upnp script and will list the devices in the box created in tool.
This was working fine.
But when i again press the scan button, it gives me following error:
Traceback (most recent call last):
File "tool\ui\main.py", line 508, in updateDevices
upnp_script.main("server", localHostAddress)
File "tool\ui\upnp_script.py", line 90, in main
reactor.run()
File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1191, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1171, in startRunning
ReactorBase.startRunning(self)
File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 683, in startRunning
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable
Main function of upnp script:
def main(mode, iface):
klass = Server if mode == 'server' else Client
obj = klass
obj(iface)
reactor.run()
There is server class which is sending M-search command(upnp) for discovering devices.
MS = 'M-SEARCH * HTTP/1.1\r\nHOST: %s:%d\r\nMAN: "ssdp:discover"\r\nMX: 2\r\nST: ssdp:all\r\n\r\n' % (SSDP_ADDR, SSDP_PORT)
In server class constructor, after sending m-search i am stooping reactor
reactor.callLater(10, reactor.stop)
From google i found that, we cannot restart a reactor beacause it is its limitation.
http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#WhycanttheTwistedsreactorberestarted
Please guide me how can i modify my code so that i am able to scan devices more than 1 time and don't get this "reactor not restartable error"
In response to "Please guide me how can i modify my code...", you haven't provided enough code that I would know how to specifically guide you, I would need to understand the (twisted part) of the logic around your scan/search.
If I were to offer a generic design/pattern/mental-model for the "twisted reactor" though, I would say think of it as your programs main loop. (thinking about the reactor that way is what makes the problem obvious to me anyway...)
I.E. most long running programs have a form something like
def main():
while(True):
check_and_update_some_stuff()
sleep 10
That same code in twisted is more like:
def main():
# the LoopingCall adds the given function to the reactor loop
l = task.LoopingCall(check_and_update_some_stuff)
l.start(10.0)
reactor.run() # <--- this is the endless while loop
If you think of the reactor as "the endless loop that makes up the main() of my program" then you'll understand why no-one is bothering to add support for "restarting" the reactor. Why would you want to restart an endless loop? Instead of stopping the core of your program, you should instead only surgically stop the task inside that is complete, leaving the main loop untouched.
You seem to be implying that the current code will keep "sending m-search"s endlessly when the reactor is running. So change your sending code so it stops repeating the "send" (... I can't tell you how to do this because you didn't provide code, but for instance, a LoopingCall can be turned off by calling its .stop method.
Runnable example as follows:
#!/usr/bin/python
from twisted.internet import task
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ServerFactory
class PollingIOThingy(object):
def __init__(self):
self.sendingcallback = None # Note I'm pushing sendToAll into here in main()
self.l = None # Also being pushed in from main()
self.iotries = 0
def pollingtry(self):
self.iotries += 1
if self.iotries > 5:
print "stoping this task"
self.l.stop()
return()
print "Polling runs: " + str(self.iotries)
if self.sendingcallback:
self.sendingcallback("Polling runs: " + str(self.iotries) + "\n")
class MyClientConnections(Protocol):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
class MyServerFactory(ServerFactory):
protocol = MyClientConnections
def __init__(self):
self.clients = []
def sendToAll(self, message):
for c in self.clients:
c.transport.write(message)
# Normally I would define a class of ServerFactory here but I'm going to
# hack it into main() as they do in the twisted chat, to make things shorter
def main():
client_connection_factory = MyServerFactory()
polling_stuff = PollingIOThingy()
# the following line is what this example is all about:
polling_stuff.sendingcallback = client_connection_factory.sendToAll
# push the client connections send def into my polling class
# if you want to run something ever second (instead of 1 second after
# the end of your last code run, which could vary) do:
l = task.LoopingCall(polling_stuff.pollingtry)
polling_stuff.l = l
l.start(1.0)
# from: https://twistedmatrix.com/documents/12.3.0/core/howto/time.html
reactor.listenTCP(5000, client_connection_factory)
reactor.run()
if __name__ == '__main__':
main()
This script has extra cruft in it that you might not care about, so just focus on the self.l.stop() in PollingIOThingys polling try method and the l related stuff in main() to illustrates the point.
(this code comes from SO: Persistent connection in twisted check that question if you want to know what the extra bits are about)
I am trying to connect to a remote MySql server from my local machine.
I want to run it whenever the DEBUG constant is set to true.
Here's the script:
import select
import SocketServer
import sys
import threading
import paramiko
SSH_PORT = 22
DEFAULT_PORT = 4000
g_verbose = True
class ForwardServer (SocketServer.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
class Handler (SocketServer.BaseRequestHandler):
def handle(self):
try:
chan = self.ssh_transport.open_channel('direct-tcpip',
(self.chain_host, self.chain_port),
self.request.getpeername())
except Exception, e:
verbose('Incoming request to %s:%d failed: %s' % (self.chain_host,
self.chain_port,
repr(e)))
return
if chan is None:
verbose('Incoming request to %s:%d was rejected by the SSH server.' %
(self.chain_host, self.chain_port))
return
verbose('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
chan.getpeername(), (self.chain_host, self.chain_port)))
while True:
r, w, x = select.select([self.request, chan], [], [])
if self.request in r:
data = self.request.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
self.request.send(data)
chan.close()
self.request.close()
verbose('Tunnel closed from %r' % (self.request.getpeername(),))
def forward_tunnel(local_port, remote_host, remote_port, transport):
# this is a little convoluted, but lets me configure things for the Handler
# object. (SocketServer doesn't give Handlers any way to access the outer
# server normally.)
class SubHander (Handler):
chain_host = remote_host
chain_port = remote_port
ssh_transport = transport
ForwardServer(('', local_port), SubHander).serve_forever()
def verbose(s):
if g_verbose:
print s
HELP = """\
Set up a forward tunnel across an SSH server, using paramiko. A local port
(given with -p) is forwarded across an SSH session to an address:port from
the SSH server. This is similar to the openssh -L option.
"""
def forward():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
print 'connecting'
client.connect('*******', username='***', password='****!')
print 'connected'
except Exception, e:
print '*** Failed to connect to %s:%d: %r' % ('*****', 22, e)
sys.exit(1)
try:
forward_tunnel(3306, '127.0.0.1', 3306, client.get_transport())
except SystemExit:
print 'C-c: Port forwarding stopped.'
sys.exit(0)
I have two problems here:
1) I don't know how and when to call my forward function when django raises.
2) When I access django locally and run the script from the console I get the following exception:
exception happened during
processing of request from
('127.0.0.1', 41872) Traceback (most
recent call last): File
"/usr/lib/python2.6/SocketServer.py",
line 558, in process_request_thread
self.finish_request(request, client_address) File
"/usr/lib/python2.6/SocketServer.py",
line 320, in finish_request
self.RequestHandlerClass(request, client_address, self) File
"/usr/lib/python2.6/SocketServer.py",
line 615, in init
self.handle() File "/home/omer/Aptana Studio 3
Workspace/Website/src/ssh_tunnel/tunnel.py",
line 51, in handle
verbose('Tunnel closed from %r' % (self.request.getpeername(),)) File
"", line 1, in getpeername
File "/usr/lib/python2.6/socket.py",
line 165, in _dummy
raise error(EBADF, 'Bad file descriptor') error: [Errno 9] Bad file
descriptor
Was this a bad idea to begin with?
Should I do this manually every time?
I don't think it's a bad idea.
I don't think you need to do it manually.
The exception is a bug in paramiko's forward code sample. This has been addressed by jhalcrow in the pull request here:
https://github.com/paramiko/paramiko/pull/36
This post has some code to do it in a more event driven way, i.e if you wanted to call it via some web event hooks in your django code or the like:
Paramiko SSH Tunnel Shutdown Issue
humm, i didn't try this, but if you are on linux, could you run
ssh -L 3306:localhost:3306 remote.host.ip
through python system call when DEBUG is set?
also if you are on Windows, try putty with port forwarding