socket.send() is raising AttributeError: 'tuple' object has no attribute 'send' - python-2.7

I was developing a program that individual elements from the list to another machine (sender-server,reciever-client). I am sharing my program below
-------------------------client.py------------------------
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 4444 # Reserve a port for your service.
s.connect((host, port))
s.send("Hi server1")
while True:
a=int(s.recv(1024))
tmp=0
while tmp<=a:
print s.recv(1024)
tmp=tmp+1
----------------------------------server.py------------------------------
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 4444 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5)
print "Server listening"
while True:
c=s.accept()
b=['a','b']
d=len(b)
a=str(d)
c.send(a)
for i in range(0,len(b)):
tmp=str(b[i])
c.send(tmp)
When I run both server and client, the server raises this:
Traceback (most recent call last):
File "server.py", line 14, in <module>
c.send(a)
AttributeError: 'tuple' object has no attribute 'send'

You'll have to fix the indentation on line 11 of client.py.
socket.accept() returns a tuple (conn, addr) where conn is a socket object. You have to use that object in line 14 to send things. What you're doing is calling send() from the entire tuple which has no method named send and so the AttributeError gets raised. I'd suggest changing line 11 to c = s.accept()[0].

Related

with conn: AttributeError: __exit__ when using socket to receive message

I have a script, in python, that need to communicate with another script, in java, through socket, the python script will only receive messages and i'm using a library called mininet to do my stuff and apparently it cant run on python3 so i need to use python2. I currently use python2.7.15+
I searched on stack and i didn't find this problem in the context that i have, apparently the with statement don't implement a context manager and for some reason i need this on the socket fucntion (i'm very unfamiliar with python so if this situation is easily explained by a basic python knowledge forgive me)
def start_socket(self):
HOST = 'localhost'
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
while 1:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
message = data.decode(encoding='UTF-8')
if (message == 'start7'):
topo_size = "7"
s.close()
elif (message == 'start6'):
topo_size = "6"
s.close()
elif (message == 'start5'):
topo_size = "5"
s.close()
elif (message == 'start4'):
topo_size = "4"
s.close()
elif (message == 'start3'):
topo_size = "3"
s.close()
elif (message == 'start2'):
topo_size = "2"
s.close()
elif (message == 'start1'):
topo_size = "1"
s.close()
break
This function is called on a main function that need to wait a order from the other script in java, and after determines what message is between this seven possible messages, he breaks and proceed with the code. The expected here is that it check what messages is and proceed with the code but what happening is: when the function is called the code blocks until receive a connection and when the other script connects, the python script throws an error saying that there's a problem with the line:
with conn:
The complete error is:
Socket created
Socket now listening
Traceback (most recent call last):
File "script_initial.py", line 669, in <module>
teste.run_topo()
File "script_initial.py", line 643, in run_topo
self.start_socket()
File "script_initial.py", line 584, in start_socket
with conn:
AttributeError: __exit__
In Python 2.7 the socket object does not support the context manager interface. You therefore cannot use the with statement with the socket object and have to explicitly call its close method after you're done using it.
Change:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
...
to:
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024)
...
conn.close()

raise MQMIError(rv[-2], rv[-1]) pymqi.MQMIError: MQI Error. Comp: 2, Reason 2085: FAILED: MQRC_UNKNOWN_OBJECT_NAME

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.

zmq.error.ZMQError: No such device

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.

serial.serialutil.SerialException: could not open port

I tried to communicate Python and Arduino with pyserial on Win8
but it had error like this
Traceback (most recent call last):
File "C:\Users\Fon\Desktop\x.py", line 7, in <module>
ser.open() # open serial port
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': WindowsError(2, 'The system cannot find the file specified.')
this is my code
import serial
ser = serial.Serial()
ser.port = 3 # serial port
ser.baudrate = 115200 # set baudrate 115200
ser.timeout = 60 # timeout 60 second
ser.open() # open serial port
while True:
ser.write('l') # send '1' to port to get light
light = ser.read(4)
print "light", light
in this code I tried to open port 'COM4', I already check this port is available and I already tried another port but it not worked any port.
Am I using wrong port? or something? ;(

Using paramiko to tunnel an MySql port when django starts

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