TypeError: cannot concatenate 'str' - python

I got this error TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects when i tried to change directory in the ftp.
ftp.py
from ftplib import FTP
ftp = FTP()
class FTPClient():
connection_id = None
login_ok = False
message_array = []
def __init__(self):
pass
def log_message(self, message, clear=True):
if clear:
self.message_array = message
def get_message(self):
return self.message_array
def connect(self, server, ftp_user, ftp_password, is_passive = False):
self.connection_id = ftp.connect(server)
login_result = ftp.login(user=ftp_user, passwd=ftp_password)
ftp.set_pasv(is_passive)
if not self.connection_id or not login_result:
self.log_message("FTP Connection has Failed")
self.log_message("Attempted to connect to {0} for {1}".format(server, ftp_user))
return False
else:
self.log_message("Connected to {0} for {1}".format(server, ftp_user))
self.login_ok = True
return True
def make_dir(self, directory):
if ftp.mkd(directory):
self.log_message("Directory {0} created successfully".format(directory))
return True
else:
self.log_message("Failed creating directory")
return False
def change_directory(self, directory):
if ftp.cwd(directory):
self.log_message("Current Directory is now {0}".format(ftp.pwd))
else:
self.log_message("Can't change Directory")
def upload_file(self, file_from, file_to):
if file_from.endswith(('.csv', '.txt')):
with open(file_from, 'r') as f:
self.connection_id.storelines("Uploaded from {0} to {1}".format(file_from, file_to), f)
else:
with open(file_from, 'rb') as f:
self.connection_id.storebinary('Uploaded from {0} to {1}'.format(file_from, file_to), f)
ftp_obj = FTPClient()
FTP_HOST = "yyy"
FTP_USER = "xxx"
FTP_PASS = "zzz"
ftp_obj.connect(FTP_HOST, FTP_USER, FTP_PASS)
print(ftp_obj.get_message())
FILE_FROM = "config.txt"
FILE_TO = ftp_obj.change_directory(dir)
ftp_obj.upload_file(FILE_FROM, FILE_TO)
print(ftp_obj.get_message())
Full traceback:
Connected to yyy for xxx
Traceback (most recent call last):
File "C:/Users/Ajay/PycharmProjects/database/test.py", line 67, in <module>
FILE_TO = ftp_obj.change_directory(dir)
File "C:/Users/Ajay/PycharmProjects/database/test.py", line 44, in change_directory
if ftp.cwd(directory):
File "C:\Python27\lib\ftplib.py", line 552, in cwd
cmd = 'CWD ' + dirname
TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects
Whats happening there ? and why this error ?

Error is here:
FILE_TO = ftp_obj.change_directory(dir)
you have not declared dir var, builtin function dir passed instead.

Related

why do I get [Errno 2]?

so I have created a server that as for now does a very simple task, it suppose to send to the browser a packet whitch contains the string "datatatata".
but it does'nt work, when running it and sending a request from browser, I keep getting [Errno 2]. the request is of course HTTP request
the code:
import socket
# functions
def get_file_data(filename):
pass
def handle_client_request(file_path, client_socket):
file_to_return = open(file_path, 'rb')
file_content = file_to_return.read()
client_socket.send(file_content)
def validate_client_request(client_request):
# checks validation of request. for now validation is set to true
validation = True
# checks for requested URL
desired_file_name = ""
for i in client_request[5::]:
if i != " ":
desired_file_name += i
else:
break
# checking file type
file_type = ""
if desired_file_name == "favicon":
file_type = "ico"
elif desired_file_name == "abstruct" or desired_file_name == "":
file_type = "jpg"
elif desired_file_name == "loading":
file_type = "gif"
if file_type == "":
validation = False
file_path = "C:\\Users\\hadad\\Desktop\\webroot\\imgs\\" + desired_file_name + "." + file_type
return validation, file_path
def handle_client(client_socket):
client_request = client_socket.recv(1024).decode()
valid_request, file_path = validate_client_request(client_request)
if valid_request:
handle_client_request(file_path, client_socket)
else:
client_socket.send("unvalid request. connection ended".encode())
client_socket.close()
def main():
server_socket = socket.socket()
server_socket.bind(("0.0.0.0", 80))
server_socket.listen()
# everlasting loop
while True:
client_socket, client_address = server_socket.accept()
handle_client(client_socket)
if __name__ == '__main__':
main()
the error:
Traceback (most recent call last):
File "C:/Networks/hed/good_server.py", line 64, in <module>
main()
File "C:/Networks/hed/good_server.py", line 60, in main
handle_client(client_socket)
File "C:/Networks/hed/good_server.py", line 46, in handle_client
handle_client_request(file_path, client_socket)
File "C:/Networks/hed/good_server.py", line 11, in handle_client_request
file_to_return = open(file_path, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\hadad\\Desktop\\webroot\\imgs\\abstruct.jpg'

python AttributeError: 'mHID' object has no attribute 'dict'

I am trying to make a makeblock mblock implementation with python and i found this api on github but it uses python 2.7 and i am using python 3.8 so i am trying to configure the code so it can run on python 3.8 but i ran into an error which is
init mBot
bot
<lib.mBot.mSerial object at 0x02CE9898>
start with serial
<lib.mBot.mHID object at 0x02E2B310>
self.device = mHID()
'mHID' object has no attribute 'dict'
Exception in thread Thread-2:
self.start()
Traceback (most recent call last):
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 154, in __onRead
start with HID
--------------------
n = self.device.inWaiting()
<lib.mBot.mBot object at 0x002FF640>
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 96, in inWaiting
--------------------
Error in sys.excepthook:
buf = self.dict.device.read(64)
Traceback (most recent call last):
AttributeError: 'mHID' object has no attribute 'dict'
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 134, in excepthook
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.close()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 142, in close
self.device.close()
self.run()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 106, in close
File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self.dict.device.close()
AttributeError: 'mHID' object has no attribute 'dict'
Original exception was:
Traceback (most recent call last):
File "c:/Users/abdsak11/OneDrive - Lärande/Dokument/GitHub/python-for-mbot/test.py", line 15, in <module>
self._target(*self._args, **self._kwargs)
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 163, in __onRead
bot.doMove(50,50)
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 179, in doMove
self.close()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 142, in close
self.__writePackage(bytearray([0xff,0x55,0x7,0x0,0x2,0x5]+self.short2bytes(-leftSpeed)+self.short2bytes(rightSpeed)))
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 278, in short2bytes
self.device.close()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 106, in close
return [ord(val[0]),ord(val[1])]
TypeError: ord() expected string of length 1, but int found
self.dict.device.close()
AttributeError: 'mHID' object has no attribute 'dict'
'mHID' object has no attribute 'dict'
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 154, in __onRead
n = self.device.inWaiting()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 96, in inWaiting
buf = self.dict.device.read(64)
AttributeError: 'mHID' object has no attribute 'dict'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 163, in __onRead
self.close()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 142, in close
self.device.close()
File "c:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\python-for-mbot\lib\mBot.py", line 106, in close
self.dict.device.close()
AttributeError: 'mHID' object has no attribute 'dict'
So what i am trying to do is to control and upload code to my mbot via usb COM3 serial and thats the error that i am getting i tried everthing but its not working and i cant seem to figure out the cause of the error.
mbot.py
this is the main api that i found
import serial
import sys,time
import signal
from time import ctime,sleep
import glob,struct
from multiprocessing import Process,Manager,Array
import threading
import hid
class mSerial():
ser = None
def __init__(self):
print (self)
def start(self, port):
self.ser = serial.Serial(port,115200)
def device(self):
return self.ser
def serialPorts(self):
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
s = serial.Serial()
s.port = port
s.close()
result.append(port)
return result
def writePackage(self,package):
self.ser.write(package)
sleep(0.01)
def read(self):
return self.ser.read()
def isOpen(self):
return self.ser.isOpen()
def inWaiting(self):
return self.ser.inWaiting()
def close(self):
self.ser.close()
class mHID():
def __init__(self):
print (self)
def start(self):
print ("starting start \n\n")
self.manager = Manager()
print("manager pass \n\n")
self.dict = self.manager.dict()
print("dict pass \n\n")
self.dict.device = hid.device()
print("dict device pass \n\n")
self.dict.device.open(0x0416, 0xffff)
print("dict device open pass \n\n")
self.dict.device.hid_set_nonblocking(self.device,1)
print ("start")
self.buffer = []
self.bufferIndex = 0
def enumerate(self):
print ("enumerate")
for dev in self.dict.device.enumerate():
print ('------------------------------------------------------------')
print (dev.description())
def writePackage(self,package):
buf = []
buf += [0, len(package)]
for i in range(len(package)):
buf += [package[i]]
n = self.dict.device.write(buf)
sleep(0.01)
def read(self):
c = self.buffer[0]
self.buffer = self.buffer[1:]
return chr(c)
def isOpen(self):
return True
def inWaiting(self):
buf = self.dict.device.read(64)
l = 0
if len(buf)>0:
l = buf[0]
if l>0:
for i in range(0,l):
self.buffer += [buf[i+1]]
return len(self.buffer)
def close(self):
self.dict.device.close()
class mBot():
def __init__(self):
print ("init mBot")
signal.signal(signal.SIGINT, self.exit)
self.manager = Manager()
self.__selectors = self.manager.dict()
self.buffer = []
self.bufferIndex = 0
self.isParseStart = False
self.exiting = False
self.isParseStartIndex = 0
def startWithSerial(self, port):
self.device = mSerial()
self.device.start(port)
self.start()
def startWithHID(self):
self.device = mHID()
print ("self.device = mHID()\n \n")
self.device.start()
print ("self.device.start()\n \n")
self.start()
print ("self.start()\n \n")
def excepthook(self, exctype, value, traceback):
self.close()
def start(self):
sys.excepthook = self.excepthook
th = threading.Thread(target=self.__onRead,args=(self.onParse,))
th.start()
def close(self):
self.device.close()
def exit(self, signal, frame):
self.exiting = True
sys.exit(0)
def __onRead(self,callback):
while 1:
if(self.exiting==True):
break
try:
if self.device.isOpen()==True:
n = self.device.inWaiting()
for i in range(n):
r = ord(self.device.read())
callback(r)
sleep(0.01)
else:
sleep(0.5)
except Exception as ex:
print (str(ex))
self.close()
sleep(1)
def __writePackage(self,pack):
self.device.writePackage(pack)
def doRGBLed(self,port,slot,index,red,green,blue):
self.__writePackage(bytearray([0xff,0x55,0x9,0x0,0x2,0x8,port,slot,index,red,green,blue]))
def doRGBLedOnBoard(self,index,red,green,blue):
self.doRGBLed(0x7,0x2,index,red,green,blue)
def doMotor(self,port,speed):
self.__writePackage(bytearray([0xff,0x55,0x6,0x0,0x2,0xa,port]+self.short2bytes(speed)))
def doMove(self,leftSpeed,rightSpeed):
self.__writePackage(bytearray([0xff,0x55,0x7,0x0,0x2,0x5]+self.short2bytes(-leftSpeed)+self.short2bytes(rightSpeed)))
def doServo(self,port,slot,angle):
self.__writePackage(bytearray([0xff,0x55,0x6,0x0,0x2,0xb,port,slot,angle]))
def doBuzzer(self,buzzer,time=0):
self.__writePackage(bytearray([0xff,0x55,0x7,0x0,0x2,0x22]+self.short2bytes(buzzer)+self.short2bytes(time)))
def doSevSegDisplay(self,port,display):
self.__writePackage(bytearray([0xff,0x55,0x8,0x0,0x2,0x9,port]+self.float2bytes(display)))
def doIROnBoard(self,message):
self.__writePackage(bytearray([0xff,0x55,len(message)+3,0x0,0x2,0xd,message]))
def requestLightOnBoard(self,extID,callback):
self.requestLight(extID,8,callback)
def requestLight(self,extID,port,callback):
self.__doCallback(extID,callback)
self.__writePackage(bytearray([0xff,0x55,0x4,extID,0x1,0x3,port]))
def requestButtonOnBoard(self,extID,callback):
self.__doCallback(extID,callback)
self.__writePackage(bytearray([0xff,0x55,0x4,extID,0x1,0x1f,0x7]))
def requestIROnBoard(self,extID,callback):
self.__doCallback(extID,callback)
self.__writePackage(bytearray([0xff,0x55,0x3,extID,0x1,0xd]))
def requestUltrasonicSensor(self,extID,port,callback):
self.__doCallback(extID,callback)
self.__writePackage(bytearray([0xff,0x55,0x4,extID,0x1,0x1,port]))
def requestLineFollower(self,extID,port,callback):
self.__doCallback(extID,callback)
self.__writePackage(bytearray([0xff,0x55,0x4,extID,0x1,0x11,port]))
def onParse(self, byte):
position = 0
value = 0
self.buffer+=[byte]
bufferLength = len(self.buffer)
if bufferLength >= 2:
if (self.buffer[bufferLength-1]==0x55 and self.buffer[bufferLength-2]==0xff):
self.isParseStart = True
self.isParseStartIndex = bufferLength-2
if (self.buffer[bufferLength-1]==0xa and self.buffer[bufferLength-2]==0xd and self.isParseStart==True):
self.isParseStart = False
position = self.isParseStartIndex+2
extID = self.buffer[position]
position+=1
type = self.buffer[position]
position+=1
# 1 byte 2 float 3 short 4 len+string 5 double
if type == 1:
value = self.buffer[position]
if type == 2:
value = self.readFloat(position)
if(value<-255 or value>1023):
value = 0
if type == 3:
value = self.readShort(position)
if type == 4:
value = self.readString(position)
if type == 5:
value = self.readDouble(position)
if(type<=5):
self.responseValue(extID,value)
self.buffer = []
def readFloat(self, position):
v = [self.buffer[position], self.buffer[position+1],self.buffer[position+2],self.buffer[position+3]]
return struct.unpack('<f', struct.pack('4B', *v))[0]
def readShort(self, position):
v = [self.buffer[position], self.buffer[position+1]]
return struct.unpack('<h', struct.pack('2B', *v))[0]
def readString(self, position):
l = self.buffer[position]
position+=1
s = ""
for i in Range(l):
s += self.buffer[position+i].charAt(0)
return s
def readDouble(self, position):
v = [self.buffer[position], self.buffer[position+1],self.buffer[position+2],self.buffer[position+3]]
return struct.unpack('<f', struct.pack('4B', *v))[0]
def responseValue(self, extID, value):
self.__selectors["callback_"+str(extID)](value)
def __doCallback(self, extID, callback):
self.__selectors["callback_"+str(extID)] = callback
def float2bytes(self,fval):
val = struct.pack("f",fval)
return [ord(val[0]),ord(val[1]),ord(val[2]),ord(val[3])]
def short2bytes(self,sval):
val = struct.pack("h",sval)
return [ord(val[0]),ord(val[1])]
test.py
this is the test file that i am working with
from lib.mBot import *
if __name__ == "__main__":
bot = mBot()
print ("bot \n\n")
bot.startWithSerial("COM3")
print ("start with serial\n\n")
bot.startWithHID()
print ("start with HID \n\n")
print(f'--------------------\n')
print (bot)
print(f'--------------------\n')
bot.doMove(50,50)
I believe your trouble is here:
class mHID():
def __init__(self):
print (self)
def start(self):
# ...
self.dict = self.manager.dict()
# ...
def close(self):
self.dict.device.close()
You should always define your instance attributes in __init__(), at least with an initial value of None, even if you plan to change them later.
Additionally, whenever you have a situation where "A must be called before B", you should write the code to properly handle when B is called without A. In this case, what should close() do if start() was never called? For simplicity, I'm just having it do nothing, but you may consider raising an exception.
class mHID():
def __init__(self):
print (self)
self.dct = None
def start(self):
# ...
self.dct = self.manager.dict()
# ...
def close(self):
if self.dct:
self.dct.device.close()
You'll notice I also renamed self.dict to self.dct. Although the former name may technically be allowable because of the self. namespace, dict is actually a built-in class. Under various circumstances, you could wind up dealing with shadowing. In the very least, it's confusing to always have to remind oneself that "this isn't the built-in dict, but an instance variable instead.
(Possible aside: is there a particular reason why you don't want to call start() from the initializer?)
WARNING: This is not a simple case of "copy and paste the answer". I've illustrated a couple of design principles here that you should incorporate into the rest of your code.

Python - Quickfix : getHeader() attribute error when trying to login

I am using Quickfix and I modified my toAdmin function to insert the username and password into the logon message. I adapted my code from the c++ instructions but I got a weird getHeader() attribute error.
The traceback is the following :
<20151223-10:48:31.142, FIX.4.2:MATHCLIENT1->CSTEST, event>
(Created session)
Type 1 for order , 2 to exit and d to debug.
<20151223-10:48:31.149, FIX.4.2:CLIENT1->TEST, event>
(Connecting to hostX on port Y)
Traceback (most recent call last):
File "initiator.py", line 28, in toAdmin
message.getHeader ().getField (msgType)
File "C:\Users\user\Anaconda\lib\site-packages\quickfix.py", line 27015, in <lambda>
__getattr__ = lambda self, name: _swig_getattr(self, SessionID, name)
File "C:\Users\user\Anaconda\lib\site-packages\quickfix.py", line 57, in _swig_getattr
raise AttributeError(name)
AttributeError: getHeader
My code follows below :
import sys
import time
import thread
import argparse
from datetime import datetime
import quickfix as fix
class Application(fix.Application):
orderID = 0
execID = 0
def gen_ord_id(self):
global orderID
orderID+=1
return orderID
def onCreate(self, sessionID):
return
def onLogon(self, sessionID):
self.sessionID = sessionID
print ("Successful Logon to session '%s'." % sessionID.toString())
return
def onLogout(self, sessionID): return
def toAdmin(self, sessionID, message):
msgType = fix.MsgType ()
message.getHeader ().getField (msgType)
if (msgType.getValue () == fix.MsgType_Logon):
print 'Logging on.'
# message.setField (fix.Password (settings.get (self.sessionID).getString ("Password")))
# message.setField (fix.Username (settings.get (self.sessionID).getString ("Username")))
message.setField(fix.Password('password'))
message.setField(fix.Username('username'))
message.setField (fix.ResetSeqNumFlag (True))
return
def fromAdmin(self, sessionID, message):
return
def toApp(self, sessionID, message):
print "Sent the following message: %s" % message.toString()
return
def fromApp(self, message, sessionID):
print "Received the following message: %s" % message.toString()
return
def genOrderID(self):
self.orderID = self.orderID+1
return `self.orderID`
def genExecID(self):
self.execID = self.execID+1
return `self.execID`
def put_order(self):
print("Creating the following order: ")
trade = fix.Message()
trade.getHeader().setField(fix.BeginString(fix.BeginString_FIX50)) #
trade.getHeader().setField(fix.MsgType(fix.MsgType_NewOrderSingle)) #39=D
trade.setField(fix.ClOrdID(self.genExecID())) #11=Unique order
trade.setField(fix.HandlInst(fix.HandlInst_MANUAL_ORDER_BEST_EXECUTION)) #21=3 (Manual order, best executiona)
trade.setField(fix.Symbol('SMBL')) #55=SMBL ?
trade.setField(fix.Side(fix.Side_BUY)) #43=1 Buy
trade.setField(fix.OrdType(fix.OrdType_LIMIT)) #40=2 Limit order
trade.setField(fix.OrderQty(100)) #38=100
trade.setField(fix.Price(10))
print trade.toString()
fix.Session.sendToTarget(trade, self.sessionID)
def main(config_file):
try:
settings = fix.SessionSettings(config_file)
application = Application()
storeFactory = fix.FileStoreFactory(settings)
# logFactory = fix.FileLogFactory(settings)
logFactory = fix.ScreenLogFactory(settings)
initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory)
initiator.start()
print 'Type 1 for order , 2 to exit and d to debug.'
while 1:
input = raw_input()
if input == '1':
print "Putin Order"
application.put_order()
if input == '2':
sys.exit(0)
if input == 'd':
import pdb
pdb.set_trace()
else:
print "Valid input is 1 for order, 2 for exit"
continue
except (fix.ConfigError, fix.RuntimeError), e:
print e
if __name__=='__main__':
# logfile = open('errorlog.txt','w')
# original_stderr = sys.stderr
# sys.stderr = logfile
parser = argparse.ArgumentParser(description='FIX Client')
parser.add_argument('file_name', type=str, help='Name of configuration file')
args = parser.parse_args()
main(args.file_name)
# sys.stderr = original_stderr
# logfile.close()
This looks mostly correct, however, I believe you have entered your arguments in the wrong order. Try defining your function as follows:
def toAdmin(self, message, sessionID):

emulate file-like behavior in python

I'm writing a script, where I have to dump some columns of tables from an SQL database into a file, and transfer it via FTP.
Because dumps can get really big, my Idea was to write a FakeFile which querys row by row from a cursor in its readline method and pass it to ftplib.FTP.storlines.
This is what I have so far:
import ftplib
import MySQLdb
def MySQLFakeFile(object):
'''
Simulates a read-only file, which dumps rows on demand.
Use this, to pass it to the FTP protocol to make the dump more efficient,
without the need to dump it somewhere and copy it over the net afterwords
'''
def __init__(self, cursor, delimeter, table_name, query):
self.cursor = cursor
self.delimeter = delimeter
self.table_name = table_name
#query is something along select ... FROM %s
self.cursor.execute(query, table_name)
self._has_written_index = False
#file attrs
self.closed = False
self.name = table_name + ".csv"
self.encoding = "utf-8"
self.mode = "r"
def close(self):
self.cursor.close()
self.closed = True
def flush(self):
'''No-OP'''
pass
def read(self, size):
pass
def readline(self, size):
if not self._has_written_index:
ret = []
for desc in self.cursor.description:
ret.append(desc[0])
self._has_written_index = True
else:
ret = self.cursor.fetchone()
if not ret:
return None
s = ""
for col in ret:
s += str(col) + self.delimeter
return s + "\n"
def readlines(self, size):
ret = []
line = self.readline()
while line:
ret.append(line)
line = self.readline()
def write(self, string):
raise Exception("cannot write to a MySQLFakeFile")
def writelines(self, lines)
raise Exception("cannot write to a MySQLFakeFile")
db = MySQLdb("host", "user", "pass", "db")
ftp = ftplib.FTP("host", "user", "pass")
fakeFile = MySQLFakeFile(db.cursor(), ";", "tableName", "SELECT * FROM %s")
ftp.storlines("STOR tableName.csv", fakeFile)
gives me
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/ftplib.py", line 496, in storlines
if len(buf) > self.maxline:
TypeError: object of type 'NoneType' has no len()
What am I doing wrong, and whats the NoneType here?
Your readline returns None instead of empty string "" when reached end-of-rows.
Your readlines returns nothing.
def readlines(self, size):
ret = []
while True:
line = self.readline()
if not line:
break
ret.append(line)
return ret

AttributeError: addinfourl instance has no __call__ method

the first pass everything works fine, but the second run I get AttributeError: instance has no __ addinfourl call__ method, i don't know what's wrong
first pass
True
Status:OK
second pass File "D:\python\New Status\status.py", line 124, in print mainstatus.bite() File "D:\python\New Status\status.py", line 109, in bite s = file("cc.beat") AttributeError: addinfourl instance has no call method
basically use it to check the status of a server and confirm that another process is active
failure = True
servestatus = False
def log():
a=open ("Status.failures","a")
now = datetime.now()
tiempo = str (now) +" - Error\n"
a.write(tiempo)
a.close ()
class mainstatus(object):
#staticmethod
def xmlstatus():
try:
file = urllib2.urlopen('http://192.168.1.110:9900/admin/xmlstatus?user=&password=')
data = file.read()
file.close()
dom = parseString(data)
xmlTag = dom.getElementsByTagName('Status')[0].toxml()
xmlData=xmlTag.replace('<Status>','').replace('</Status>','')
if xmlTag == "<Status>OK</Status>":
stat = True
except:
stat= False
return stat
#staticmethod
def hola():
x = "test"
return x
#staticmethod
def internet(url):
try:
response=urllib2.urlopen(url,timeout=1)
return True
except urllib2.URLError as err: pass
return False
#staticmethod
def heartbeat():
a=open ("heart.beat","w")
now = datetime.now()
tiempo = str (now.minute)
a.write(tiempo)
a.close ()
#staticmethod
def push(mensaje):
#Miguel
conn = httplib.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.urlencode({
"token": "",
"user": "",
"message": mensaje,
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()
#Gerswin
conn = httplib.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.urlencode({
"token": "",
"user": "",
"message": mensaje,
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()
#staticmethod
def colam():
cola = 0
for root, dirs, files in os.walk("\\\\Server0\\smsdata\\Q"):
for file in files:
if file.endswith('.req'):
cola += 1
#staticmethod
def wol():
HOST = "192.168.1.1"
user = "root"
password = "16745665"
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("/usr/sbin/wol -i 192.168.1.255 -p 7 00:11:25:36:08:FE\n")
tn.write("exit\n")
tn.read_all()
#staticmethod
def bite():
now = datetime.now()
tiempo = (now.minute)
s = file("cc.beat")
status = int(s.readline())
s.close()
vivo = tiempo - status
if (vivo > 0):
return False
else:
return True
count = 5
print "Server Status Check: Runing..."
while (count < 9):
time.sleep(2)
print mainstatus.bite()
pulso = True
if pulso == False:
#os.startfile('check.exe')
print "activa"
else:
pass
status = mainstatus.internet("http://192.168.1.110:9900")
mainstatus.heartbeat()
if status == True:
if mainstatus.xmlstatus() == True:
print '\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bStatus:OK',
if failure == True:
accion = os.system('net stop "NowSMS"')
file = urllib2.urlopen('http://sql.gerswin.com/status.php?status=OK')
data = file.read()
file.close()
failure = False
if mainstatus.colam() >= 20 and servestatus == False:
accion = os.system('net start "NowSMS"')
mainstatus.push("Server Overload, Server 2 Running")
servestatus = True
else:
if mainstatus.colam() < 20 and servestatus == True:
mainstatus.push("Stoping Server 2")
accion = os.system('net stop "NowSMS"')
servestatus = False
file = urllib2.urlopen('http://sql.gerswin.com/status.php?status=OK')
data = file.read()
file.close()
else:
print '\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bStatus: Modem Failure',
mainstatus.wol()
if servestatus == False:
accion = os.system('net start "NowSMS"')
mainstatus.push("Modem Failure, Server 2 Running")
log()
file = urllib2.urlopen('http://sql.gerswin.com/status.php?status=2')
data = file.read()
file.close()
servestatus = True
else:
print "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bStatus: Fallo Server",
mainstatus.wol()
if servestatus == False:
accion = os.system('net start "NowSMS"')
file = urllib2.urlopen('http://192.168.1.110:9900?ok=no')
data = file.read()
file.close()
log()
mainstatus.push("Server Failure, Server 2 Running")
servestatus = True
You are using the global variable file to store the result of a urllib2.urlopen() call, twice. But you are also expecting to use it as the built-in file() type:
>>> import urllib2
>>> file('/dev/random')
<open file '/dev/random', mode 'r' at 0x10c8ee660>
>>> file = urllib2.urlopen('http://stackoverflow.com')
>>> file('/dev/random')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: addinfourl instance has no __call__ method
Don't do that. Don't shadow built-ins with your own variable name, and don't use file(). Use the open() function instead.
>>> open('/dev/random')
<open file '/dev/random', mode 'r' at 0x10c8ee6f0>
>>> response = urllib2.urlopen('http://stackoverflow.com')

Categories

Resources